Coverage Report

Created: 2023-10-04 01:15

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ                   https://dearimgui.com/faq
11
// - Getting Started       https://dearimgui.com/getting-started
12
// - Homepage              https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6478 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
// - Tests & Automation    https://github.com/ocornut/imgui_test_engine
19
20
// For first-time users having issues compiling/linking/running/loading fonts:
21
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
23
24
// Copyright (c) 2014-2023 Omar Cornut
25
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26
// See LICENSE.txt for copyright and licensing details (standard MIT License).
27
// This library is free but needs your support to sustain development and maintenance.
28
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
29
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
30
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
31
32
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
33
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
34
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
35
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
36
// to a better solution or official support for them.
37
38
/*
39
40
Index of this file:
41
42
DOCUMENTATION
43
44
- MISSION STATEMENT
45
- CONTROLS GUIDE
46
- PROGRAMMER GUIDE
47
  - READ FIRST
48
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
49
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
50
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
51
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
52
- API BREAKING CHANGES (read me when you update!)
53
- FREQUENTLY ASKED QUESTIONS (FAQ)
54
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
55
56
CODE
57
(search for "[SECTION]" in the code to find them)
58
59
// [SECTION] INCLUDES
60
// [SECTION] FORWARD DECLARATIONS
61
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
62
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
63
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
64
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
65
// [SECTION] MISC HELPERS/UTILITIES (File functions)
66
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
67
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
68
// [SECTION] ImGuiStorage
69
// [SECTION] ImGuiTextFilter
70
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
71
// [SECTION] ImGuiListClipper
72
// [SECTION] STYLING
73
// [SECTION] RENDER HELPERS
74
// [SECTION] INITIALIZATION, SHUTDOWN
75
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
76
// [SECTION] INPUTS
77
// [SECTION] ERROR CHECKING
78
// [SECTION] LAYOUT
79
// [SECTION] SCROLLING
80
// [SECTION] TOOLTIPS
81
// [SECTION] POPUPS
82
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
83
// [SECTION] DRAG AND DROP
84
// [SECTION] LOGGING/CAPTURING
85
// [SECTION] SETTINGS
86
// [SECTION] LOCALIZATION
87
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
88
// [SECTION] DOCKING
89
// [SECTION] PLATFORM DEPENDENT HELPERS
90
// [SECTION] METRICS/DEBUGGER WINDOW
91
// [SECTION] DEBUG LOG WINDOW
92
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
93
94
*/
95
96
//-----------------------------------------------------------------------------
97
// DOCUMENTATION
98
//-----------------------------------------------------------------------------
99
100
/*
101
102
 MISSION STATEMENT
103
 =================
104
105
 - Easy to use to create code-driven and data-driven tools.
106
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
107
 - Easy to hack and improve.
108
 - Minimize setup and maintenance.
109
 - Minimize state storage on user side.
110
 - Minimize state synchronization.
111
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
112
 - Efficient runtime and memory consumption.
113
114
 Designed primarily for developers and content-creators, not the typical end-user!
115
 Some of the current weaknesses (which we aim to address in the future) includes:
116
117
 - Doesn't look fancy.
118
 - Limited layout features, intricate layouts are typically crafted in code.
119
120
121
 CONTROLS GUIDE
122
 ==============
123
124
 - MOUSE CONTROLS
125
   - Mouse wheel:                   Scroll vertically.
126
   - SHIFT+Mouse wheel:             Scroll horizontally.
127
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
128
   - Click ^, Double-Click title:   Collapse window.
129
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
130
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
131
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
132
133
 - TEXT EDITOR
134
   - Hold SHIFT or Drag Mouse:      Select text.
135
   - CTRL+Left/Right:               Word jump.
136
   - CTRL+Shift+Left/Right:         Select words.
137
   - CTRL+A or Double-Click:        Select All.
138
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
139
   - CTRL+Z, CTRL+Y:                Undo, Redo.
140
   - ESCAPE:                        Revert text to its original value.
141
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
142
143
 - KEYBOARD CONTROLS
144
   - Basic:
145
     - Tab, SHIFT+Tab               Cycle through text editable fields.
146
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
147
     - CTRL+Click                   Input text into a Slider or Drag widget.
148
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
149
     - Tab, SHIFT+Tab:              Cycle through every items.
150
     - Arrow keys                   Move through items using directional navigation. Tweak value.
151
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
152
     - Enter                        Activate item (prefer text input when possible).
153
     - Space                        Activate item (prefer tweaking with arrows when possible).
154
     - Escape                       Deactivate item, leave child window, close popup.
155
     - Page Up, Page Down           Previous page, next page.
156
     - Home, End                    Scroll to top, scroll to bottom.
157
     - Alt                          Toggle between scrolling layer and menu layer.
158
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
159
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
160
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
161
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
162
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
163
164
 - GAMEPAD CONTROLS
165
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
166
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
167
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
168
   - Backend support: backend needs to:
169
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
170
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
171
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
172
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
173
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
174
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
175
176
 - REMOTE INPUTS SHARING & MOUSE EMULATION
177
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
178
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
179
     in order to share your PC mouse/keyboard.
180
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
181
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
182
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
183
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
184
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
185
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
186
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
187
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
188
189
190
 PROGRAMMER GUIDE
191
 ================
192
193
 READ FIRST
194
 ----------
195
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
196
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
197
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
198
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
199
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
200
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
201
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
202
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
203
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
204
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
205
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
206
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
207
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
208
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
209
   If you get an assert, read the messages and comments around the assert.
210
 - This codebase aims to be highly optimized:
211
   - A typical idle frame should never call malloc/free.
212
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
213
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
214
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
215
 - This codebase aims to be both highly opinionated and highly flexible:
216
   - This code works because of the things it choose to solve or not solve.
217
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
218
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
219
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
220
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
221
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
222
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
223
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
224
     (so don't use ImVector in your code or at our own risk!).
225
   - Building: We don't use nor mandate a build system for the main library.
226
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
227
     This is also because providing a build system for the main library would be of little-value.
228
     The build problems are almost never coming from the main library but from specific backends.
229
230
231
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
232
 ----------------------------------------------
233
 - Update submodule or copy/overwrite every file.
234
 - About imconfig.h:
235
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
236
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
237
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
238
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
239
240
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
241
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
242
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
243
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
244
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
245
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
246
   likely be a comment about it. Please report any issue to the GitHub page!
247
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
248
 - Try to keep your copy of Dear ImGui reasonably up to date!
249
250
251
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
252
 ---------------------------------------------------------------
253
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
254
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
255
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
256
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
257
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
258
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
259
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
260
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
261
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
262
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
263
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
264
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
265
266
267
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
268
 --------------------------------------
269
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
270
 The sub-folders in examples/ contain examples applications following this structure.
271
272
     // Application init: create a dear imgui context, setup some options, load fonts
273
     ImGui::CreateContext();
274
     ImGuiIO& io = ImGui::GetIO();
275
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
276
     // TODO: Fill optional fields of the io structure later.
277
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
278
279
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
280
     ImGui_ImplWin32_Init(hwnd);
281
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
282
283
     // Application main loop
284
     while (true)
285
     {
286
         // Feed inputs to dear imgui, start new frame
287
         ImGui_ImplDX11_NewFrame();
288
         ImGui_ImplWin32_NewFrame();
289
         ImGui::NewFrame();
290
291
         // Any application code here
292
         ImGui::Text("Hello, world!");
293
294
         // Render dear imgui into screen
295
         ImGui::Render();
296
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
297
         g_pSwapChain->Present(1, 0);
298
     }
299
300
     // Shutdown
301
     ImGui_ImplDX11_Shutdown();
302
     ImGui_ImplWin32_Shutdown();
303
     ImGui::DestroyContext();
304
305
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
306
307
     // Application init: create a dear imgui context, setup some options, load fonts
308
     ImGui::CreateContext();
309
     ImGuiIO& io = ImGui::GetIO();
310
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
311
     // TODO: Fill optional fields of the io structure later.
312
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
313
314
     // Build and load the texture atlas into a texture
315
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
316
     int width, height;
317
     unsigned char* pixels = nullptr;
318
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
319
320
     // At this point you've got the texture data and you need to upload that to your graphic system:
321
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
322
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
323
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
324
     io.Fonts->SetTexID((void*)texture);
325
326
     // Application main loop
327
     while (true)
328
     {
329
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
330
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
331
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
332
        io.DisplaySize.x = 1920.0f;             // set the current display width
333
        io.DisplaySize.y = 1280.0f;             // set the current display height here
334
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
335
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
336
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
337
338
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
339
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
340
        ImGui::NewFrame();
341
342
        // Most of your application code here
343
        ImGui::Text("Hello, world!");
344
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
345
        MyGameRender(); // may use any Dear ImGui functions as well!
346
347
        // Render dear imgui, swap buffers
348
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
349
        ImGui::EndFrame();
350
        ImGui::Render();
351
        ImDrawData* draw_data = ImGui::GetDrawData();
352
        MyImGuiRenderFunction(draw_data);
353
        SwapBuffers();
354
     }
355
356
     // Shutdown
357
     ImGui::DestroyContext();
358
359
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
360
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
361
 Please read the FAQ and example applications for details about this!
362
363
364
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
365
 ---------------------------------------------
366
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
367
368
    void MyImGuiRenderFunction(ImDrawData* draw_data)
369
    {
370
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
371
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
372
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
373
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
374
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
375
       ImVec2 clip_off = draw_data->DisplayPos;
376
       for (int n = 0; n < draw_data->CmdListsCount; n++)
377
       {
378
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
379
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
380
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
381
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
382
          {
383
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
384
             if (pcmd->UserCallback)
385
             {
386
                 pcmd->UserCallback(cmd_list, pcmd);
387
             }
388
             else
389
             {
390
                 // Project scissor/clipping rectangles into framebuffer space
391
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
392
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
393
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
394
                     continue;
395
396
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
397
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
398
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
399
                 // - Clipping coordinates are provided in imgui coordinates space:
400
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
401
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
402
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
403
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
404
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
405
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
406
407
                 // The texture for the draw call is specified by pcmd->GetTexID().
408
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
409
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
410
411
                 // Render 'pcmd->ElemCount/3' indexed triangles.
412
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
413
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
414
             }
415
          }
416
       }
417
    }
418
419
420
 API BREAKING CHANGES
421
 ====================
422
423
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
424
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
425
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
426
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
427
428
(Docking/Viewport Branch)
429
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
430
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
431
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
432
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
433
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
434
435
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
436
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
437
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
438
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
439
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
440
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
441
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
442
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
443
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
444
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
445
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
446
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
447
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
448
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
449
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
450
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
451
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
452
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
453
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
454
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
455
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
456
                           - ListBoxFooter()  -> use EndListBox()
457
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
458
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
459
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
460
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
461
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
462
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
463
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
464
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
465
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
466
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
467
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
468
                         it has been frequently requested by people to use our own. We had an opt-in define which was
469
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
470
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
471
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
472
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
473
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
474
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
475
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
476
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
477
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
478
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
479
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
480
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
481
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
482
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
483
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
484
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
485
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
486
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
487
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
488
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
489
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
490
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
491
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
492
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
493
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
494
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
495
                         - previously this would make the window content size ~200x200:
496
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
497
                         - instead, please submit an item:
498
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
499
                         - alternative:
500
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
501
                         - content size is now only extended when submitting an item!
502
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
503
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
504
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
505
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
506
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
507
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
508
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
509
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
510
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
511
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
512
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
513
                        - Official backends from 1.87+                  -> no issue.
514
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
515
                        - Custom backends not writing to io.NavInputs[] -> no issue.
516
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
517
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
518
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
519
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
520
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
521
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
522
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
523
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
524
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
525
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
526
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
527
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
528
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
529
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
530
                       read https://github.com/ocornut/imgui/issues/4921 for details.
531
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
532
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
533
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
534
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
535
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
536
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
537
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
538
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
539
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
540
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
541
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
542
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
543
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
544
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
545
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
546
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
547
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
548
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
549
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
550
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
551
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
552
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
553
                        - if you are using official backends from the source tree: you have nothing to do.
554
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
555
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
556
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
557
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
558
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
559
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
560
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
561
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
562
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
563
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
564
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
565
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
566
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
567
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
568
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
569
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
570
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
571
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
572
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
573
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
574
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
575
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
576
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
577
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
578
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
579
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
580
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
581
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
582
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
583
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
584
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
585
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
586
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
587
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
588
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
589
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
590
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
591
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
592
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
593
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
594
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
595
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
596
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
597
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
598
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
599
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
600
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
601
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
602
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
603
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
604
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
605
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
606
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
607
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
608
                       - if you omitted the 'power' parameter (likely!), you are not affected.
609
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
610
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
611
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
612
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
613
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
614
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
615
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
616
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
617
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
618
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
619
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
620
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
621
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
622
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
623
                       - ShowTestWindow()                    -> use ShowDemoWindow()
624
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
625
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
626
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
627
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
628
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
629
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
630
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
631
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
632
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
633
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
634
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
635
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
636
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
637
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
638
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
639
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
640
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
641
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
642
                       - ImFont::Glyph                       -> use ImFontGlyph
643
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
644
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
645
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
646
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
647
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
648
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
649
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
650
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
651
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
652
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
653
                       Please reach out if you are affected.
654
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
655
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
656
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
657
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
658
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
659
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
660
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
661
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
662
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
663
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
664
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
665
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
666
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
667
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
668
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
669
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
670
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
671
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
672
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
673
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
674
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
675
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
676
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
677
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
678
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
679
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
680
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
681
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
682
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
683
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
684
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
685
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
686
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
687
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
688
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
689
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
690
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
691
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
692
                       consistent with other functions. Kept redirection functions (will obsolete).
693
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
694
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
695
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
696
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
697
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
698
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
699
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
700
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
701
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
702
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
703
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
704
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
705
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
706
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
707
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
708
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
709
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
710
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
711
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
712
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
713
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
714
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
715
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
716
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
717
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
718
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
719
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
720
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
721
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
722
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
723
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
724
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
725
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
726
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
727
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
728
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
729
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
730
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
731
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
732
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
733
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
734
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
735
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
736
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
737
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
738
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
739
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
740
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
741
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
742
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
743
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
744
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
745
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
746
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
747
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
748
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
749
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
750
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
751
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
752
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
753
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
754
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
755
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
756
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
757
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
758
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
759
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
760
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
761
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
762
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
763
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
764
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
765
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
766
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
767
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
768
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
769
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
770
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
771
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
772
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
773
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
774
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
775
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
776
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
777
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
778
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
779
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
780
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
781
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
782
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
783
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
784
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
785
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
786
                     - the signature of the io.RenderDrawListsFn handler has changed!
787
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
788
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
789
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
790
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
791
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
792
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
793
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
794
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
795
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
796
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
797
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
798
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
799
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
800
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
801
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
802
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
803
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
804
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
805
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
806
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
807
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
808
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
809
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
810
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
811
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
812
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
813
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
814
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
815
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
816
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
817
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
818
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
819
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
820
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
821
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
822
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
823
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
824
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
825
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
826
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
827
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
828
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
829
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
830
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
831
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
832
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
833
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
834
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
835
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
836
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
837
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
838
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
839
840
841
 FREQUENTLY ASKED QUESTIONS (FAQ)
842
 ================================
843
844
 Read all answers online:
845
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
846
 Read all answers locally (with a text editor or ideally a Markdown viewer):
847
   docs/FAQ.md
848
 Some answers are copied down here to facilitate searching in code.
849
850
 Q&A: Basics
851
 ===========
852
853
 Q: Where is the documentation?
854
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
855
    - Run the examples/ applications and explore them.
856
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
857
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
858
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
859
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
860
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
861
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
862
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
863
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
864
    - Your programming IDE is your friend, find the type or function declaration to find comments
865
      associated with it.
866
867
 Q: What is this library called?
868
 Q: Which version should I get?
869
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
870
 >> See https://www.dearimgui.com/faq for details.
871
872
 Q&A: Integration
873
 ================
874
875
 Q: How to get started?
876
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
877
878
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
879
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
880
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
881
882
 Q. How can I enable keyboard or gamepad controls?
883
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
884
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
885
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
886
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
887
 >> See https://www.dearimgui.com/faq
888
889
 Q&A: Usage
890
 ----------
891
892
 Q: About the ID Stack system..
893
   - Why is my widget not reacting when I click on it?
894
   - How can I have widgets with an empty label?
895
   - How can I have multiple widgets with the same label?
896
   - How can I have multiple windows with the same label?
897
 Q: How can I display an image? What is ImTextureID, how does it work?
898
 Q: How can I use my own math types instead of ImVec2?
899
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
900
 Q: How can I display custom shapes? (using low-level ImDrawList API)
901
 >> See https://www.dearimgui.com/faq
902
903
 Q&A: Fonts, Text
904
 ================
905
906
 Q: How should I handle DPI in my application?
907
 Q: How can I load a different font than the default?
908
 Q: How can I easily use icons in my application?
909
 Q: How can I load multiple fonts?
910
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
911
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
912
913
 Q&A: Concerns
914
 =============
915
916
 Q: Who uses Dear ImGui?
917
 Q: Can you create elaborate/serious tools with Dear ImGui?
918
 Q: Can you reskin the look of Dear ImGui?
919
 Q: Why using C++ (as opposed to C)?
920
 >> See https://www.dearimgui.com/faq
921
922
 Q&A: Community
923
 ==============
924
925
 Q: How can I help?
926
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
927
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
928
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
929
      Also see https://github.com/ocornut/imgui/wiki/Sponsors
930
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
931
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
932
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
933
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
934
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
935
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
936
937
*/
938
939
//-------------------------------------------------------------------------
940
// [SECTION] INCLUDES
941
//-------------------------------------------------------------------------
942
943
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
944
#define _CRT_SECURE_NO_WARNINGS
945
#endif
946
947
#ifndef IMGUI_DEFINE_MATH_OPERATORS
948
#define IMGUI_DEFINE_MATH_OPERATORS
949
#endif
950
951
#include "imgui.h"
952
#ifndef IMGUI_DISABLE
953
#include "imgui_internal.h"
954
955
// System includes
956
#include <stdio.h>      // vsnprintf, sscanf, printf
957
#include <stdint.h>     // intptr_t
958
959
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
960
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
961
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
962
#endif
963
964
// [Windows] OS specific includes (optional)
965
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
966
#define IMGUI_DISABLE_WIN32_FUNCTIONS
967
#endif
968
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
969
#ifndef WIN32_LEAN_AND_MEAN
970
#define WIN32_LEAN_AND_MEAN
971
#endif
972
#ifndef NOMINMAX
973
#define NOMINMAX
974
#endif
975
#ifndef __MINGW32__
976
#include <Windows.h>        // _wfopen, OpenClipboard
977
#else
978
#include <windows.h>
979
#endif
980
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
981
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
982
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
983
#endif
984
#endif
985
986
// [Apple] OS specific includes
987
#if defined(__APPLE__)
988
#include <TargetConditionals.h>
989
#endif
990
991
// Visual Studio warnings
992
#ifdef _MSC_VER
993
#pragma warning (disable: 4127)             // condition expression is constant
994
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
995
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
996
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
997
#endif
998
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
999
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1000
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1001
#endif
1002
1003
// Clang/GCC warnings with -Weverything
1004
#if defined(__clang__)
1005
#if __has_warning("-Wunknown-warning-option")
1006
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1007
#endif
1008
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1009
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1010
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1011
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1012
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1013
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1014
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1015
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1016
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1017
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1018
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1019
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1020
#elif defined(__GNUC__)
1021
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1022
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1023
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1024
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1025
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1026
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1027
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1028
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1029
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1030
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1031
#endif
1032
1033
// Debug options
1034
125k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1035
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1036
1037
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1038
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1039
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1040
1041
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1042
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1043
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1044
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1045
1046
// Tooltip offset
1047
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1048
1049
// Docking
1050
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1051
1052
//-------------------------------------------------------------------------
1053
// [SECTION] FORWARD DECLARATIONS
1054
//-------------------------------------------------------------------------
1055
1056
static void             SetCurrentWindow(ImGuiWindow* window);
1057
static void             FindHoveredWindow();
1058
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1059
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1060
1061
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1062
1063
// Settings
1064
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1065
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1066
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1067
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1068
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1069
1070
// Platform Dependents default implementation for IO functions
1071
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1072
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1073
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1074
1075
namespace ImGui
1076
{
1077
// Navigation
1078
static void             NavUpdate();
1079
static void             NavUpdateWindowing();
1080
static void             NavUpdateWindowingOverlay();
1081
static void             NavUpdateCancelRequest();
1082
static void             NavUpdateCreateMoveRequest();
1083
static void             NavUpdateCreateTabbingRequest();
1084
static float            NavUpdatePageUpPageDown();
1085
static inline void      NavUpdateAnyRequestFlag();
1086
static void             NavUpdateCreateWrappingRequest();
1087
static void             NavEndFrame();
1088
static bool             NavScoreItem(ImGuiNavItemData* result);
1089
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1090
static void             NavProcessItem();
1091
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1092
static ImVec2           NavCalcPreferredRefPos();
1093
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1094
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1095
static void             NavRestoreLayer(ImGuiNavLayer layer);
1096
static int              FindWindowFocusIndex(ImGuiWindow* window);
1097
1098
// Error Checking and Debug Tools
1099
static void             ErrorCheckNewFrameSanityChecks();
1100
static void             ErrorCheckEndFrameSanityChecks();
1101
static void             UpdateDebugToolItemPicker();
1102
static void             UpdateDebugToolStackQueries();
1103
1104
// Inputs
1105
static void             UpdateKeyboardInputs();
1106
static void             UpdateMouseInputs();
1107
static void             UpdateMouseWheel();
1108
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1109
1110
// Misc
1111
static void             UpdateSettings();
1112
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1113
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1114
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1115
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1116
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1117
static void             RenderDimmedBackgrounds();
1118
1119
// Viewports
1120
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1121
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1122
static void             DestroyViewport(ImGuiViewportP* viewport);
1123
static void             UpdateViewportsNewFrame();
1124
static void             UpdateViewportsEndFrame();
1125
static void             WindowSelectViewport(ImGuiWindow* window);
1126
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1127
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1128
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1129
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1130
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1131
static int              FindPlatformMonitorForRect(const ImRect& r);
1132
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1133
1134
}
1135
1136
//-----------------------------------------------------------------------------
1137
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1138
//-----------------------------------------------------------------------------
1139
1140
// DLL users:
1141
// - Heaps and globals are not shared across DLL boundaries!
1142
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1143
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1144
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1145
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1146
1147
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1148
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1149
//   Change to a different context by calling ImGui::SetCurrentContext().
1150
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1151
//   If you want thread-safety to allow N threads to access N different contexts:
1152
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1153
//         struct ImGuiContext;
1154
//         extern thread_local ImGuiContext* MyImGuiTLS;
1155
//         #define GImGui MyImGuiTLS
1156
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1157
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1158
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1159
// - DLL users: read comments above.
1160
#ifndef GImGui
1161
ImGuiContext*   GImGui = NULL;
1162
#endif
1163
1164
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1165
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1166
// - DLL users: read comments above.
1167
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1168
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1169
1.17k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1170
#else
1171
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1172
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1173
#endif
1174
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1175
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1176
static void*                GImAllocatorUserData = NULL;
1177
1178
//-----------------------------------------------------------------------------
1179
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1180
//-----------------------------------------------------------------------------
1181
1182
ImGuiStyle::ImGuiStyle()
1183
1
{
1184
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1185
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1186
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1187
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1188
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1189
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1190
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1191
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1192
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1193
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1194
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1195
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1196
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1197
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1198
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1199
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1200
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1201
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. CellPadding.y may be altered between different rows.
1202
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1203
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1204
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1205
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1206
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1207
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1208
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1209
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1210
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1211
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1212
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1213
1
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1214
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1215
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1216
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1217
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1218
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1219
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1220
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1221
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1222
1
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1223
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1224
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1225
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1226
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1227
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1228
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1229
1230
    // Behaviors
1231
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1232
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1233
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1234
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1235
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1236
1237
    // Default theme
1238
1
    ImGui::StyleColorsDark(this);
1239
1
}
1240
1241
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1242
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1243
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1244
0
{
1245
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1246
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1247
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1248
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1249
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1250
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1251
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1252
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1253
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1254
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1255
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1256
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1257
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1258
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1259
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1260
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1261
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1262
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1263
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1264
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1265
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1266
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1267
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1268
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1269
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1270
0
}
1271
1272
ImGuiIO::ImGuiIO()
1273
1
{
1274
    // Most fields are initialized with zero
1275
1
    memset(this, 0, sizeof(*this));
1276
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1277
1278
    // Settings
1279
1
    ConfigFlags = ImGuiConfigFlags_None;
1280
1
    BackendFlags = ImGuiBackendFlags_None;
1281
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1282
1
    DeltaTime = 1.0f / 60.0f;
1283
1
    IniSavingRate = 5.0f;
1284
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1285
1
    LogFilename = "imgui_log.txt";
1286
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1287
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1288
        KeyMap[i] = -1;
1289
#endif
1290
1
    UserData = NULL;
1291
1292
1
    Fonts = NULL;
1293
1
    FontGlobalScale = 1.0f;
1294
1
    FontDefault = NULL;
1295
1
    FontAllowUserScaling = false;
1296
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1297
1298
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1299
1
    ConfigDockingNoSplit = false;
1300
1
    ConfigDockingWithShift = false;
1301
1
    ConfigDockingAlwaysTabBar = false;
1302
1
    ConfigDockingTransparentPayload = false;
1303
1304
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1305
1
    ConfigViewportsNoAutoMerge = false;
1306
1
    ConfigViewportsNoTaskBarIcon = false;
1307
1
    ConfigViewportsNoDecoration = true;
1308
1
    ConfigViewportsNoDefaultParent = false;
1309
1310
    // Miscellaneous options
1311
1
    MouseDrawCursor = false;
1312
#ifdef __APPLE__
1313
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1314
#else
1315
1
    ConfigMacOSXBehaviors = false;
1316
1
#endif
1317
1
    ConfigInputTrickleEventQueue = true;
1318
1
    ConfigInputTextCursorBlink = true;
1319
1
    ConfigInputTextEnterKeepActive = false;
1320
1
    ConfigDragClickToInputText = false;
1321
1
    ConfigWindowsResizeFromEdges = true;
1322
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1323
1
    ConfigMemoryCompactTimer = 60.0f;
1324
1
    ConfigDebugBeginReturnValueOnce = false;
1325
1
    ConfigDebugBeginReturnValueLoop = false;
1326
1327
    // Inputs Behaviors
1328
1
    MouseDoubleClickTime = 0.30f;
1329
1
    MouseDoubleClickMaxDist = 6.0f;
1330
1
    MouseDragThreshold = 6.0f;
1331
1
    KeyRepeatDelay = 0.275f;
1332
1
    KeyRepeatRate = 0.050f;
1333
1334
    // Platform Functions
1335
    // Note: Initialize() will setup default clipboard/ime handlers.
1336
1
    BackendPlatformName = BackendRendererName = NULL;
1337
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1338
1
    PlatformLocaleDecimalPoint = '.';
1339
1340
    // Input (NB: we already have memset zero the entire structure!)
1341
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1342
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1343
1
    MouseSource = ImGuiMouseSource_Mouse;
1344
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1345
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1346
1
    AppAcceptingEvents = true;
1347
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1348
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1349
1
}
1350
1351
// Pass in translated ASCII characters for text input.
1352
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1353
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1354
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1355
void ImGuiIO::AddInputCharacter(unsigned int c)
1356
6.88k
{
1357
6.88k
    IM_ASSERT(Ctx != NULL);
1358
6.88k
    ImGuiContext& g = *Ctx;
1359
6.88k
    if (c == 0 || !AppAcceptingEvents)
1360
2.46k
        return;
1361
1362
4.42k
    ImGuiInputEvent e;
1363
4.42k
    e.Type = ImGuiInputEventType_Text;
1364
4.42k
    e.Source = ImGuiInputSource_Keyboard;
1365
4.42k
    e.EventId = g.InputEventsNextEventId++;
1366
4.42k
    e.Text.Char = c;
1367
4.42k
    g.InputEventsQueue.push_back(e);
1368
4.42k
}
1369
1370
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1371
// we should save the high surrogate.
1372
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1373
3.56k
{
1374
3.56k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1375
331
        return;
1376
1377
3.23k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1378
1.54k
    {
1379
1.54k
        if (InputQueueSurrogate != 0)
1380
594
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1381
1.54k
        InputQueueSurrogate = c;
1382
1.54k
        return;
1383
1.54k
    }
1384
1385
1.68k
    ImWchar cp = c;
1386
1.68k
    if (InputQueueSurrogate != 0)
1387
880
    {
1388
880
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1389
354
        {
1390
354
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1391
354
        }
1392
526
        else
1393
526
        {
1394
526
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1395
526
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1396
#else
1397
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1398
#endif
1399
526
        }
1400
1401
880
        InputQueueSurrogate = 0;
1402
880
    }
1403
1.68k
    AddInputCharacter((unsigned)cp);
1404
1.68k
}
1405
1406
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1407
78
{
1408
78
    if (!AppAcceptingEvents)
1409
0
        return;
1410
78
    while (*utf8_chars != 0)
1411
0
    {
1412
0
        unsigned int c = 0;
1413
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1414
0
        AddInputCharacter(c);
1415
0
    }
1416
78
}
1417
1418
// Clear all incoming events.
1419
void ImGuiIO::ClearEventsQueue()
1420
0
{
1421
0
    IM_ASSERT(Ctx != NULL);
1422
0
    ImGuiContext& g = *Ctx;
1423
0
    g.InputEventsQueue.clear();
1424
0
}
1425
1426
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1427
void ImGuiIO::ClearInputKeys()
1428
9.62k
{
1429
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1430
    memset(KeysDown, 0, sizeof(KeysDown));
1431
#endif
1432
1.35M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1433
1.34M
    {
1434
1.34M
        KeysData[n].Down             = false;
1435
1.34M
        KeysData[n].DownDuration     = -1.0f;
1436
1.34M
        KeysData[n].DownDurationPrev = -1.0f;
1437
1.34M
    }
1438
9.62k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1439
9.62k
    KeyMods = ImGuiMod_None;
1440
9.62k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1441
57.7k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1442
48.1k
    {
1443
48.1k
        MouseDown[n] = false;
1444
48.1k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1445
48.1k
    }
1446
9.62k
    MouseWheel = MouseWheelH = 0.0f;
1447
9.62k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1448
9.62k
}
1449
1450
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1451
// Current frame character buffer is now also cleared by ClearInputKeys().
1452
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1453
void ImGuiIO::ClearInputCharacters()
1454
{
1455
    InputQueueCharacters.resize(0);
1456
}
1457
#endif
1458
1459
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1460
14.0k
{
1461
14.0k
    ImGuiContext& g = *ctx;
1462
22.5k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1463
13.0k
    {
1464
13.0k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1465
13.0k
        if (e->Type != type)
1466
6.67k
            continue;
1467
6.35k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1468
866
            continue;
1469
5.49k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1470
945
            continue;
1471
4.54k
        return e;
1472
5.49k
    }
1473
9.51k
    return NULL;
1474
14.0k
}
1475
1476
// Queue a new key down/up event.
1477
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1478
// - bool down:          Is the key down? use false to signify a key release.
1479
// - float analog_value: 0.0f..1.0f
1480
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1481
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1482
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1483
3.55k
{
1484
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1485
3.55k
    IM_ASSERT(Ctx != NULL);
1486
3.55k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1487
0
        return;
1488
3.55k
    ImGuiContext& g = *Ctx;
1489
3.55k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1490
3.55k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1491
3.55k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1492
1493
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1494
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1495
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1496
    if (BackendUsingLegacyKeyArrays == -1)
1497
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1498
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1499
    BackendUsingLegacyKeyArrays = 0;
1500
#endif
1501
3.55k
    if (ImGui::IsGamepadKey(key))
1502
27
        BackendUsingLegacyNavInputArray = false;
1503
1504
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1505
3.55k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1506
3.55k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1507
3.55k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1508
3.55k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1509
3.55k
    if (latest_key_down == down && latest_key_analog == analog_value)
1510
783
        return;
1511
1512
    // Add event
1513
2.77k
    ImGuiInputEvent e;
1514
2.77k
    e.Type = ImGuiInputEventType_Key;
1515
2.77k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1516
2.77k
    e.EventId = g.InputEventsNextEventId++;
1517
2.77k
    e.Key.Key = key;
1518
2.77k
    e.Key.Down = down;
1519
2.77k
    e.Key.AnalogValue = analog_value;
1520
2.77k
    g.InputEventsQueue.push_back(e);
1521
2.77k
}
1522
1523
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1524
1.36k
{
1525
1.36k
    if (!AppAcceptingEvents)
1526
0
        return;
1527
1.36k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1528
1.36k
}
1529
1530
// [Optional] Call after AddKeyEvent().
1531
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1532
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1533
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1534
0
{
1535
0
    if (key == ImGuiKey_None)
1536
0
        return;
1537
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1538
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1539
0
    IM_UNUSED(native_keycode);  // Yet unused
1540
0
    IM_UNUSED(native_scancode); // Yet unused
1541
1542
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1543
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1544
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1545
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1546
        return;
1547
    KeyMap[legacy_key] = key;
1548
    KeyMap[key] = legacy_key;
1549
#else
1550
0
    IM_UNUSED(key);
1551
0
    IM_UNUSED(native_legacy_index);
1552
0
#endif
1553
0
}
1554
1555
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1556
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1557
0
{
1558
0
    AppAcceptingEvents = accepting_events;
1559
0
}
1560
1561
// Queue a mouse move event
1562
void ImGuiIO::AddMousePosEvent(float x, float y)
1563
4.24k
{
1564
4.24k
    IM_ASSERT(Ctx != NULL);
1565
4.24k
    ImGuiContext& g = *Ctx;
1566
4.24k
    if (!AppAcceptingEvents)
1567
0
        return;
1568
1569
    // Apply same flooring as UpdateMouseInputs()
1570
4.24k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1571
1572
    // Filter duplicate
1573
4.24k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1574
4.24k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1575
4.24k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1576
728
        return;
1577
1578
3.51k
    ImGuiInputEvent e;
1579
3.51k
    e.Type = ImGuiInputEventType_MousePos;
1580
3.51k
    e.Source = ImGuiInputSource_Mouse;
1581
3.51k
    e.EventId = g.InputEventsNextEventId++;
1582
3.51k
    e.MousePos.PosX = pos.x;
1583
3.51k
    e.MousePos.PosY = pos.y;
1584
3.51k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1585
3.51k
    g.InputEventsQueue.push_back(e);
1586
3.51k
}
1587
1588
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1589
5.55k
{
1590
5.55k
    IM_ASSERT(Ctx != NULL);
1591
5.55k
    ImGuiContext& g = *Ctx;
1592
5.55k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1593
5.55k
    if (!AppAcceptingEvents)
1594
0
        return;
1595
1596
    // Filter duplicate
1597
5.55k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1598
5.55k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1599
5.55k
    if (latest_button_down == down)
1600
971
        return;
1601
1602
4.58k
    ImGuiInputEvent e;
1603
4.58k
    e.Type = ImGuiInputEventType_MouseButton;
1604
4.58k
    e.Source = ImGuiInputSource_Mouse;
1605
4.58k
    e.EventId = g.InputEventsNextEventId++;
1606
4.58k
    e.MouseButton.Button = mouse_button;
1607
4.58k
    e.MouseButton.Down = down;
1608
4.58k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1609
4.58k
    g.InputEventsQueue.push_back(e);
1610
4.58k
}
1611
1612
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1613
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1614
2.21k
{
1615
2.21k
    IM_ASSERT(Ctx != NULL);
1616
2.21k
    ImGuiContext& g = *Ctx;
1617
1618
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1619
2.21k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1620
32
        return;
1621
1622
2.18k
    ImGuiInputEvent e;
1623
2.18k
    e.Type = ImGuiInputEventType_MouseWheel;
1624
2.18k
    e.Source = ImGuiInputSource_Mouse;
1625
2.18k
    e.EventId = g.InputEventsNextEventId++;
1626
2.18k
    e.MouseWheel.WheelX = wheel_x;
1627
2.18k
    e.MouseWheel.WheelY = wheel_y;
1628
2.18k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1629
2.18k
    g.InputEventsQueue.push_back(e);
1630
2.18k
}
1631
1632
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1633
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1634
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1635
0
{
1636
0
    IM_ASSERT(Ctx != NULL);
1637
0
    ImGuiContext& g = *Ctx;
1638
0
    g.InputEventsNextMouseSource = source;
1639
0
}
1640
1641
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1642
0
{
1643
0
    IM_ASSERT(Ctx != NULL);
1644
0
    ImGuiContext& g = *Ctx;
1645
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1646
0
    if (!AppAcceptingEvents)
1647
0
        return;
1648
1649
    // Filter duplicate
1650
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1651
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1652
0
    if (latest_viewport_id == viewport_id)
1653
0
        return;
1654
1655
0
    ImGuiInputEvent e;
1656
0
    e.Type = ImGuiInputEventType_MouseViewport;
1657
0
    e.Source = ImGuiInputSource_Mouse;
1658
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1659
0
    g.InputEventsQueue.push_back(e);
1660
0
}
1661
1662
void ImGuiIO::AddFocusEvent(bool focused)
1663
711
{
1664
711
    IM_ASSERT(Ctx != NULL);
1665
711
    ImGuiContext& g = *Ctx;
1666
1667
    // Filter duplicate
1668
711
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1669
711
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1670
711
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1671
223
        return;
1672
1673
488
    ImGuiInputEvent e;
1674
488
    e.Type = ImGuiInputEventType_Focus;
1675
488
    e.EventId = g.InputEventsNextEventId++;
1676
488
    e.AppFocused.Focused = focused;
1677
488
    g.InputEventsQueue.push_back(e);
1678
488
}
1679
1680
//-----------------------------------------------------------------------------
1681
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1682
//-----------------------------------------------------------------------------
1683
1684
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1685
0
{
1686
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1687
0
    ImVec2 p_last = p1;
1688
0
    ImVec2 p_closest;
1689
0
    float p_closest_dist2 = FLT_MAX;
1690
0
    float t_step = 1.0f / (float)num_segments;
1691
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1692
0
    {
1693
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1694
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1695
0
        float dist2 = ImLengthSqr(p - p_line);
1696
0
        if (dist2 < p_closest_dist2)
1697
0
        {
1698
0
            p_closest = p_line;
1699
0
            p_closest_dist2 = dist2;
1700
0
        }
1701
0
        p_last = p_current;
1702
0
    }
1703
0
    return p_closest;
1704
0
}
1705
1706
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1707
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1708
0
{
1709
0
    float dx = x4 - x1;
1710
0
    float dy = y4 - y1;
1711
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1712
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1713
0
    d2 = (d2 >= 0) ? d2 : -d2;
1714
0
    d3 = (d3 >= 0) ? d3 : -d3;
1715
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1716
0
    {
1717
0
        ImVec2 p_current(x4, y4);
1718
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1719
0
        float dist2 = ImLengthSqr(p - p_line);
1720
0
        if (dist2 < p_closest_dist2)
1721
0
        {
1722
0
            p_closest = p_line;
1723
0
            p_closest_dist2 = dist2;
1724
0
        }
1725
0
        p_last = p_current;
1726
0
    }
1727
0
    else if (level < 10)
1728
0
    {
1729
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1730
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1731
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1732
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1733
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1734
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1735
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1736
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1737
0
    }
1738
0
}
1739
1740
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1741
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1742
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1743
0
{
1744
0
    IM_ASSERT(tess_tol > 0.0f);
1745
0
    ImVec2 p_last = p1;
1746
0
    ImVec2 p_closest;
1747
0
    float p_closest_dist2 = FLT_MAX;
1748
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1749
0
    return p_closest;
1750
0
}
1751
1752
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1753
0
{
1754
0
    ImVec2 ap = p - a;
1755
0
    ImVec2 ab_dir = b - a;
1756
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1757
0
    if (dot < 0.0f)
1758
0
        return a;
1759
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1760
0
    if (dot > ab_len_sqr)
1761
0
        return b;
1762
0
    return a + ab_dir * dot / ab_len_sqr;
1763
0
}
1764
1765
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1766
0
{
1767
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1768
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1769
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1770
0
    return ((b1 == b2) && (b2 == b3));
1771
0
}
1772
1773
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1774
0
{
1775
0
    ImVec2 v0 = b - a;
1776
0
    ImVec2 v1 = c - a;
1777
0
    ImVec2 v2 = p - a;
1778
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1779
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1780
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1781
0
    out_u = 1.0f - out_v - out_w;
1782
0
}
1783
1784
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1785
0
{
1786
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1787
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1788
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1789
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1790
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1791
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1792
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1793
0
    if (m == dist2_ab)
1794
0
        return proj_ab;
1795
0
    if (m == dist2_bc)
1796
0
        return proj_bc;
1797
0
    return proj_ca;
1798
0
}
1799
1800
//-----------------------------------------------------------------------------
1801
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1802
//-----------------------------------------------------------------------------
1803
1804
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1805
int ImStricmp(const char* str1, const char* str2)
1806
0
{
1807
0
    int d;
1808
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1809
0
    return d;
1810
0
}
1811
1812
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1813
0
{
1814
0
    int d = 0;
1815
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1816
0
    return d;
1817
0
}
1818
1819
void ImStrncpy(char* dst, const char* src, size_t count)
1820
3
{
1821
3
    if (count < 1)
1822
0
        return;
1823
3
    if (count > 1)
1824
3
        strncpy(dst, src, count - 1);
1825
3
    dst[count - 1] = 0;
1826
3
}
1827
1828
char* ImStrdup(const char* str)
1829
3
{
1830
3
    size_t len = strlen(str);
1831
3
    void* buf = IM_ALLOC(len + 1);
1832
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1833
3
}
1834
1835
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1836
0
{
1837
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1838
0
    size_t src_size = strlen(src) + 1;
1839
0
    if (dst_buf_size < src_size)
1840
0
    {
1841
0
        IM_FREE(dst);
1842
0
        dst = (char*)IM_ALLOC(src_size);
1843
0
        if (p_dst_size)
1844
0
            *p_dst_size = src_size;
1845
0
    }
1846
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1847
0
}
1848
1849
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1850
0
{
1851
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1852
0
    return p;
1853
0
}
1854
1855
int ImStrlenW(const ImWchar* str)
1856
0
{
1857
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1858
0
    int n = 0;
1859
0
    while (*str++) n++;
1860
0
    return n;
1861
0
}
1862
1863
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1864
const char* ImStreolRange(const char* str, const char* str_end)
1865
0
{
1866
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1867
0
    return p ? p : str_end;
1868
0
}
1869
1870
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1871
0
{
1872
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1873
0
        buf_mid_line--;
1874
0
    return buf_mid_line;
1875
0
}
1876
1877
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1878
0
{
1879
0
    if (!needle_end)
1880
0
        needle_end = needle + strlen(needle);
1881
1882
0
    const char un0 = (char)ImToUpper(*needle);
1883
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1884
0
    {
1885
0
        if (ImToUpper(*haystack) == un0)
1886
0
        {
1887
0
            const char* b = needle + 1;
1888
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1889
0
                if (ImToUpper(*a) != ImToUpper(*b))
1890
0
                    break;
1891
0
            if (b == needle_end)
1892
0
                return haystack;
1893
0
        }
1894
0
        haystack++;
1895
0
    }
1896
0
    return NULL;
1897
0
}
1898
1899
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1900
void ImStrTrimBlanks(char* buf)
1901
0
{
1902
0
    char* p = buf;
1903
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1904
0
        p++;
1905
0
    char* p_start = p;
1906
0
    while (*p != 0)                         // Find end of string
1907
0
        p++;
1908
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1909
0
        p--;
1910
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1911
0
        memmove(buf, p_start, p - p_start);
1912
0
    buf[p - p_start] = 0;                   // Zero terminate
1913
0
}
1914
1915
const char* ImStrSkipBlank(const char* str)
1916
0
{
1917
0
    while (str[0] == ' ' || str[0] == '\t')
1918
0
        str++;
1919
0
    return str;
1920
0
}
1921
1922
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1923
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1924
// B) When buf==NULL vsnprintf() will return the output size.
1925
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1926
1927
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1928
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1929
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1930
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1931
#ifdef IMGUI_USE_STB_SPRINTF
1932
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1933
#define STB_SPRINTF_IMPLEMENTATION
1934
#endif
1935
#ifdef IMGUI_STB_SPRINTF_FILENAME
1936
#include IMGUI_STB_SPRINTF_FILENAME
1937
#else
1938
#include "stb_sprintf.h"
1939
#endif
1940
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1941
1942
#if defined(_MSC_VER) && !defined(vsnprintf)
1943
#define vsnprintf _vsnprintf
1944
#endif
1945
1946
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1947
1
{
1948
1
    va_list args;
1949
1
    va_start(args, fmt);
1950
#ifdef IMGUI_USE_STB_SPRINTF
1951
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1952
#else
1953
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1954
1
#endif
1955
1
    va_end(args);
1956
1
    if (buf == NULL)
1957
0
        return w;
1958
1
    if (w == -1 || w >= (int)buf_size)
1959
0
        w = (int)buf_size - 1;
1960
1
    buf[w] = 0;
1961
1
    return w;
1962
1
}
1963
1964
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1965
51.0k
{
1966
#ifdef IMGUI_USE_STB_SPRINTF
1967
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1968
#else
1969
51.0k
    int w = vsnprintf(buf, buf_size, fmt, args);
1970
51.0k
#endif
1971
51.0k
    if (buf == NULL)
1972
0
        return w;
1973
51.0k
    if (w == -1 || w >= (int)buf_size)
1974
0
        w = (int)buf_size - 1;
1975
51.0k
    buf[w] = 0;
1976
51.0k
    return w;
1977
51.0k
}
1978
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1979
1980
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1981
51.0k
{
1982
51.0k
    va_list args;
1983
51.0k
    va_start(args, fmt);
1984
51.0k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
1985
51.0k
    va_end(args);
1986
51.0k
}
1987
1988
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1989
51.0k
{
1990
51.0k
    ImGuiContext& g = *GImGui;
1991
51.0k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1992
0
    {
1993
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1994
0
        *out_buf = buf;
1995
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1996
0
    }
1997
51.0k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
1998
0
    {
1999
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2000
0
        const char* buf = va_arg(args, const char*);
2001
0
        *out_buf = buf;
2002
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2003
0
    }
2004
51.0k
    else
2005
51.0k
    {
2006
51.0k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2007
51.0k
        *out_buf = g.TempBuffer.Data;
2008
51.0k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2009
51.0k
    }
2010
51.0k
}
2011
2012
// CRC32 needs a 1KB lookup table (not cache friendly)
2013
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2014
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2015
static const ImU32 GCrc32LookupTable[256] =
2016
{
2017
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2018
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2019
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2020
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2021
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2022
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2023
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2024
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2025
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2026
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2027
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2028
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2029
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2030
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2031
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2032
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2033
};
2034
2035
// Known size hash
2036
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2037
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2038
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2039
51.0k
{
2040
51.0k
    ImU32 crc = ~seed;
2041
51.0k
    const unsigned char* data = (const unsigned char*)data_p;
2042
51.0k
    const ImU32* crc32_lut = GCrc32LookupTable;
2043
255k
    while (data_size-- != 0)
2044
204k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2045
51.0k
    return ~crc;
2046
51.0k
}
2047
2048
// Zero-terminated string hash, with support for ### to reset back to seed value
2049
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2050
// Because this syntax is rarely used we are optimizing for the common case.
2051
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2052
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2053
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2054
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2055
578k
{
2056
578k
    seed = ~seed;
2057
578k
    ImU32 crc = seed;
2058
578k
    const unsigned char* data = (const unsigned char*)data_p;
2059
578k
    const ImU32* crc32_lut = GCrc32LookupTable;
2060
578k
    if (data_size != 0)
2061
0
    {
2062
0
        while (data_size-- != 0)
2063
0
        {
2064
0
            unsigned char c = *data++;
2065
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2066
0
                crc = seed;
2067
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2068
0
        }
2069
0
    }
2070
578k
    else
2071
578k
    {
2072
7.77M
        while (unsigned char c = *data++)
2073
7.19M
        {
2074
7.19M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2075
54.1k
                crc = seed;
2076
7.19M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2077
7.19M
        }
2078
578k
    }
2079
578k
    return ~crc;
2080
578k
}
2081
2082
//-----------------------------------------------------------------------------
2083
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2084
//-----------------------------------------------------------------------------
2085
2086
// Default file functions
2087
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2088
2089
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2090
0
{
2091
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2092
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2093
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2094
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2095
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2096
    ImGuiContext& g = *GImGui;
2097
    g.TempBuffer.reserve((filename_wsize + mode_wsize) * sizeof(wchar_t));
2098
    wchar_t* buf = (wchar_t*)(void*)g.TempBuffer.Data;
2099
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2100
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2101
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2102
#else
2103
0
    return fopen(filename, mode);
2104
0
#endif
2105
0
}
2106
2107
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2108
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2109
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2110
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2111
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2112
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2113
2114
// Helper: Load file content into memory
2115
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2116
// This can't really be used with "rt" because fseek size won't match read size.
2117
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2118
0
{
2119
0
    IM_ASSERT(filename && mode);
2120
0
    if (out_file_size)
2121
0
        *out_file_size = 0;
2122
2123
0
    ImFileHandle f;
2124
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2125
0
        return NULL;
2126
2127
0
    size_t file_size = (size_t)ImFileGetSize(f);
2128
0
    if (file_size == (size_t)-1)
2129
0
    {
2130
0
        ImFileClose(f);
2131
0
        return NULL;
2132
0
    }
2133
2134
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2135
0
    if (file_data == NULL)
2136
0
    {
2137
0
        ImFileClose(f);
2138
0
        return NULL;
2139
0
    }
2140
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2141
0
    {
2142
0
        ImFileClose(f);
2143
0
        IM_FREE(file_data);
2144
0
        return NULL;
2145
0
    }
2146
0
    if (padding_bytes > 0)
2147
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2148
2149
0
    ImFileClose(f);
2150
0
    if (out_file_size)
2151
0
        *out_file_size = file_size;
2152
2153
0
    return file_data;
2154
0
}
2155
2156
//-----------------------------------------------------------------------------
2157
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2158
//-----------------------------------------------------------------------------
2159
2160
IM_MSVC_RUNTIME_CHECKS_OFF
2161
2162
// Convert UTF-8 to 32-bit character, process single character input.
2163
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2164
// We handle UTF-8 decoding error by skipping forward.
2165
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2166
8.53M
{
2167
8.53M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2168
8.53M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2169
8.53M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2170
8.53M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2171
8.53M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2172
8.53M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2173
8.53M
    int wanted = len + (len ? 0 : 1);
2174
2175
8.53M
    if (in_text_end == NULL)
2176
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2177
2178
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2179
    // so it is fast even with excessive branching.
2180
8.53M
    unsigned char s[4];
2181
8.53M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2182
8.53M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2183
8.53M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2184
8.53M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2185
2186
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2187
8.53M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2188
8.53M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2189
8.53M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2190
8.53M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2191
8.53M
    *out_char >>= shiftc[len];
2192
2193
    // Accumulate the various error conditions.
2194
8.53M
    int e = 0;
2195
8.53M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2196
8.53M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2197
8.53M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2198
8.53M
    e |= (s[1] & 0xc0) >> 2;
2199
8.53M
    e |= (s[2] & 0xc0) >> 4;
2200
8.53M
    e |= (s[3]       ) >> 6;
2201
8.53M
    e ^= 0x2a; // top two bits of each tail byte correct?
2202
8.53M
    e >>= shifte[len];
2203
2204
8.53M
    if (e)
2205
1.23M
    {
2206
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2207
        // One byte is consumed in case of invalid first byte of in_text.
2208
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2209
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2210
1.23M
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2211
1.23M
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2212
1.23M
    }
2213
2214
8.53M
    return wanted;
2215
8.53M
}
2216
2217
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2218
0
{
2219
0
    ImWchar* buf_out = buf;
2220
0
    ImWchar* buf_end = buf + buf_size;
2221
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2222
0
    {
2223
0
        unsigned int c;
2224
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2225
0
        *buf_out++ = (ImWchar)c;
2226
0
    }
2227
0
    *buf_out = 0;
2228
0
    if (in_text_remaining)
2229
0
        *in_text_remaining = in_text;
2230
0
    return (int)(buf_out - buf);
2231
0
}
2232
2233
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2234
0
{
2235
0
    int char_count = 0;
2236
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2237
0
    {
2238
0
        unsigned int c;
2239
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2240
0
        char_count++;
2241
0
    }
2242
0
    return char_count;
2243
0
}
2244
2245
// Based on stb_to_utf8() from github.com/nothings/stb/
2246
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2247
0
{
2248
0
    if (c < 0x80)
2249
0
    {
2250
0
        buf[0] = (char)c;
2251
0
        return 1;
2252
0
    }
2253
0
    if (c < 0x800)
2254
0
    {
2255
0
        if (buf_size < 2) return 0;
2256
0
        buf[0] = (char)(0xc0 + (c >> 6));
2257
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2258
0
        return 2;
2259
0
    }
2260
0
    if (c < 0x10000)
2261
0
    {
2262
0
        if (buf_size < 3) return 0;
2263
0
        buf[0] = (char)(0xe0 + (c >> 12));
2264
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2265
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2266
0
        return 3;
2267
0
    }
2268
0
    if (c <= 0x10FFFF)
2269
0
    {
2270
0
        if (buf_size < 4) return 0;
2271
0
        buf[0] = (char)(0xf0 + (c >> 18));
2272
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2273
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2274
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2275
0
        return 4;
2276
0
    }
2277
    // Invalid code point, the max unicode is 0x10FFFF
2278
0
    return 0;
2279
0
}
2280
2281
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2282
0
{
2283
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2284
0
    out_buf[count] = 0;
2285
0
    return out_buf;
2286
0
}
2287
2288
// Not optimal but we very rarely use this function.
2289
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2290
0
{
2291
0
    unsigned int unused = 0;
2292
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2293
0
}
2294
2295
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2296
0
{
2297
0
    if (c < 0x80) return 1;
2298
0
    if (c < 0x800) return 2;
2299
0
    if (c < 0x10000) return 3;
2300
0
    if (c <= 0x10FFFF) return 4;
2301
0
    return 3;
2302
0
}
2303
2304
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2305
0
{
2306
0
    char* buf_p = out_buf;
2307
0
    const char* buf_end = out_buf + out_buf_size;
2308
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2309
0
    {
2310
0
        unsigned int c = (unsigned int)(*in_text++);
2311
0
        if (c < 0x80)
2312
0
            *buf_p++ = (char)c;
2313
0
        else
2314
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2315
0
    }
2316
0
    *buf_p = 0;
2317
0
    return (int)(buf_p - out_buf);
2318
0
}
2319
2320
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2321
0
{
2322
0
    int bytes_count = 0;
2323
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2324
0
    {
2325
0
        unsigned int c = (unsigned int)(*in_text++);
2326
0
        if (c < 0x80)
2327
0
            bytes_count++;
2328
0
        else
2329
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2330
0
    }
2331
0
    return bytes_count;
2332
0
}
2333
2334
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2335
0
{
2336
0
    while (in_text_curr > in_text_start)
2337
0
    {
2338
0
        in_text_curr--;
2339
0
        if ((*in_text_curr & 0xC0) != 0x80)
2340
0
            return in_text_curr;
2341
0
    }
2342
0
    return in_text_start;
2343
0
}
2344
2345
IM_MSVC_RUNTIME_CHECKS_RESTORE
2346
2347
//-----------------------------------------------------------------------------
2348
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2349
// Note: The Convert functions are early design which are not consistent with other API.
2350
//-----------------------------------------------------------------------------
2351
2352
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2353
0
{
2354
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2355
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2356
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2357
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2358
0
    return IM_COL32(r, g, b, 0xFF);
2359
0
}
2360
2361
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2362
183k
{
2363
183k
    float s = 1.0f / 255.0f;
2364
183k
    return ImVec4(
2365
183k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2366
183k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2367
183k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2368
183k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2369
183k
}
2370
2371
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2372
1.05M
{
2373
1.05M
    ImU32 out;
2374
1.05M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2375
1.05M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2376
1.05M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2377
1.05M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2378
1.05M
    return out;
2379
1.05M
}
2380
2381
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2382
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2383
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2384
0
{
2385
0
    float K = 0.f;
2386
0
    if (g < b)
2387
0
    {
2388
0
        ImSwap(g, b);
2389
0
        K = -1.f;
2390
0
    }
2391
0
    if (r < g)
2392
0
    {
2393
0
        ImSwap(r, g);
2394
0
        K = -2.f / 6.f - K;
2395
0
    }
2396
2397
0
    const float chroma = r - (g < b ? g : b);
2398
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2399
0
    out_s = chroma / (r + 1e-20f);
2400
0
    out_v = r;
2401
0
}
2402
2403
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2404
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2405
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2406
0
{
2407
0
    if (s == 0.0f)
2408
0
    {
2409
        // gray
2410
0
        out_r = out_g = out_b = v;
2411
0
        return;
2412
0
    }
2413
2414
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2415
0
    int   i = (int)h;
2416
0
    float f = h - (float)i;
2417
0
    float p = v * (1.0f - s);
2418
0
    float q = v * (1.0f - s * f);
2419
0
    float t = v * (1.0f - s * (1.0f - f));
2420
2421
0
    switch (i)
2422
0
    {
2423
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2424
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2425
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2426
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2427
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2428
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2429
0
    }
2430
0
}
2431
2432
//-----------------------------------------------------------------------------
2433
// [SECTION] ImGuiStorage
2434
// Helper: Key->value storage
2435
//-----------------------------------------------------------------------------
2436
2437
// std::lower_bound but without the bullshit
2438
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2439
159k
{
2440
159k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2441
159k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2442
159k
    size_t count = (size_t)(last - first);
2443
477k
    while (count > 0)
2444
318k
    {
2445
318k
        size_t count2 = count >> 1;
2446
318k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2447
318k
        if (mid->key < key)
2448
105k
        {
2449
105k
            first = ++mid;
2450
105k
            count -= count2 + 1;
2451
105k
        }
2452
213k
        else
2453
213k
        {
2454
213k
            count = count2;
2455
213k
        }
2456
318k
    }
2457
159k
    return first;
2458
159k
}
2459
2460
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2461
void ImGuiStorage::BuildSortByKey()
2462
0
{
2463
0
    struct StaticFunc
2464
0
    {
2465
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2466
0
        {
2467
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2468
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2469
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2470
0
            return 0;
2471
0
        }
2472
0
    };
2473
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2474
0
}
2475
2476
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2477
0
{
2478
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2479
0
    if (it == Data.end() || it->key != key)
2480
0
        return default_val;
2481
0
    return it->val_i;
2482
0
}
2483
2484
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2485
0
{
2486
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2487
0
}
2488
2489
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2490
0
{
2491
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2492
0
    if (it == Data.end() || it->key != key)
2493
0
        return default_val;
2494
0
    return it->val_f;
2495
0
}
2496
2497
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2498
159k
{
2499
159k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2500
159k
    if (it == Data.end() || it->key != key)
2501
3
        return NULL;
2502
159k
    return it->val_p;
2503
159k
}
2504
2505
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2506
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2507
0
{
2508
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2509
0
    if (it == Data.end() || it->key != key)
2510
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2511
0
    return &it->val_i;
2512
0
}
2513
2514
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2515
0
{
2516
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2517
0
}
2518
2519
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2520
0
{
2521
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2522
0
    if (it == Data.end() || it->key != key)
2523
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2524
0
    return &it->val_f;
2525
0
}
2526
2527
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2528
0
{
2529
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2530
0
    if (it == Data.end() || it->key != key)
2531
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2532
0
    return &it->val_p;
2533
0
}
2534
2535
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2536
void ImGuiStorage::SetInt(ImGuiID key, int val)
2537
0
{
2538
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2539
0
    if (it == Data.end() || it->key != key)
2540
0
    {
2541
0
        Data.insert(it, ImGuiStoragePair(key, val));
2542
0
        return;
2543
0
    }
2544
0
    it->val_i = val;
2545
0
}
2546
2547
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2548
0
{
2549
0
    SetInt(key, val ? 1 : 0);
2550
0
}
2551
2552
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2553
0
{
2554
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2555
0
    if (it == Data.end() || it->key != key)
2556
0
    {
2557
0
        Data.insert(it, ImGuiStoragePair(key, val));
2558
0
        return;
2559
0
    }
2560
0
    it->val_f = val;
2561
0
}
2562
2563
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2564
3
{
2565
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2566
3
    if (it == Data.end() || it->key != key)
2567
3
    {
2568
3
        Data.insert(it, ImGuiStoragePair(key, val));
2569
3
        return;
2570
3
    }
2571
0
    it->val_p = val;
2572
0
}
2573
2574
void ImGuiStorage::SetAllInt(int v)
2575
0
{
2576
0
    for (int i = 0; i < Data.Size; i++)
2577
0
        Data[i].val_i = v;
2578
0
}
2579
2580
//-----------------------------------------------------------------------------
2581
// [SECTION] ImGuiTextFilter
2582
//-----------------------------------------------------------------------------
2583
2584
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2585
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2586
0
{
2587
0
    InputBuf[0] = 0;
2588
0
    CountGrep = 0;
2589
0
    if (default_filter)
2590
0
    {
2591
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2592
0
        Build();
2593
0
    }
2594
0
}
2595
2596
bool ImGuiTextFilter::Draw(const char* label, float width)
2597
0
{
2598
0
    if (width != 0.0f)
2599
0
        ImGui::SetNextItemWidth(width);
2600
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2601
0
    if (value_changed)
2602
0
        Build();
2603
0
    return value_changed;
2604
0
}
2605
2606
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2607
0
{
2608
0
    out->resize(0);
2609
0
    const char* wb = b;
2610
0
    const char* we = wb;
2611
0
    while (we < e)
2612
0
    {
2613
0
        if (*we == separator)
2614
0
        {
2615
0
            out->push_back(ImGuiTextRange(wb, we));
2616
0
            wb = we + 1;
2617
0
        }
2618
0
        we++;
2619
0
    }
2620
0
    if (wb != we)
2621
0
        out->push_back(ImGuiTextRange(wb, we));
2622
0
}
2623
2624
void ImGuiTextFilter::Build()
2625
0
{
2626
0
    Filters.resize(0);
2627
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2628
0
    input_range.split(',', &Filters);
2629
2630
0
    CountGrep = 0;
2631
0
    for (ImGuiTextRange& f : Filters)
2632
0
    {
2633
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2634
0
            f.b++;
2635
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2636
0
            f.e--;
2637
0
        if (f.empty())
2638
0
            continue;
2639
0
        if (f.b[0] != '-')
2640
0
            CountGrep += 1;
2641
0
    }
2642
0
}
2643
2644
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2645
0
{
2646
0
    if (Filters.empty())
2647
0
        return true;
2648
2649
0
    if (text == NULL)
2650
0
        text = "";
2651
2652
0
    for (const ImGuiTextRange& f : Filters)
2653
0
    {
2654
0
        if (f.empty())
2655
0
            continue;
2656
0
        if (f.b[0] == '-')
2657
0
        {
2658
            // Subtract
2659
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2660
0
                return false;
2661
0
        }
2662
0
        else
2663
0
        {
2664
            // Grep
2665
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2666
0
                return true;
2667
0
        }
2668
0
    }
2669
2670
    // Implicit * grep
2671
0
    if (CountGrep == 0)
2672
0
        return true;
2673
2674
0
    return false;
2675
0
}
2676
2677
//-----------------------------------------------------------------------------
2678
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2679
//-----------------------------------------------------------------------------
2680
2681
// On some platform vsnprintf() takes va_list by reference and modifies it.
2682
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2683
#ifndef va_copy
2684
#if defined(__GNUC__) || defined(__clang__)
2685
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2686
#else
2687
#define va_copy(dest, src) (dest = src)
2688
#endif
2689
#endif
2690
2691
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2692
2693
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2694
0
{
2695
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2696
2697
    // Add zero-terminator the first time
2698
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2699
0
    const int needed_sz = write_off + len;
2700
0
    if (write_off + len >= Buf.Capacity)
2701
0
    {
2702
0
        int new_capacity = Buf.Capacity * 2;
2703
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2704
0
    }
2705
2706
0
    Buf.resize(needed_sz);
2707
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2708
0
    Buf[write_off - 1 + len] = 0;
2709
0
}
2710
2711
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2712
0
{
2713
0
    va_list args;
2714
0
    va_start(args, fmt);
2715
0
    appendfv(fmt, args);
2716
0
    va_end(args);
2717
0
}
2718
2719
// Helper: Text buffer for logging/accumulating text
2720
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2721
0
{
2722
0
    va_list args_copy;
2723
0
    va_copy(args_copy, args);
2724
2725
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2726
0
    if (len <= 0)
2727
0
    {
2728
0
        va_end(args_copy);
2729
0
        return;
2730
0
    }
2731
2732
    // Add zero-terminator the first time
2733
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2734
0
    const int needed_sz = write_off + len;
2735
0
    if (write_off + len >= Buf.Capacity)
2736
0
    {
2737
0
        int new_capacity = Buf.Capacity * 2;
2738
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2739
0
    }
2740
2741
0
    Buf.resize(needed_sz);
2742
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2743
0
    va_end(args_copy);
2744
0
}
2745
2746
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2747
0
{
2748
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2749
0
    if (old_size == new_size)
2750
0
        return;
2751
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2752
0
        LineOffsets.push_back(EndOffset);
2753
0
    const char* base_end = base + new_size;
2754
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2755
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2756
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2757
0
    EndOffset = ImMax(EndOffset, new_size);
2758
0
}
2759
2760
//-----------------------------------------------------------------------------
2761
// [SECTION] ImGuiListClipper
2762
//-----------------------------------------------------------------------------
2763
2764
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2765
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2766
static bool GetSkipItemForListClipping()
2767
0
{
2768
0
    ImGuiContext& g = *GImGui;
2769
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2770
0
}
2771
2772
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2773
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2774
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2775
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2776
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2777
{
2778
    ImGuiContext& g = *GImGui;
2779
    ImGuiWindow* window = g.CurrentWindow;
2780
    if (g.LogEnabled)
2781
    {
2782
        // If logging is active, do not perform any clipping
2783
        *out_items_display_start = 0;
2784
        *out_items_display_end = items_count;
2785
        return;
2786
    }
2787
    if (GetSkipItemForListClipping())
2788
    {
2789
        *out_items_display_start = *out_items_display_end = 0;
2790
        return;
2791
    }
2792
2793
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2794
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2795
    ImRect rect = window->ClipRect;
2796
    if (g.NavMoveScoringItems)
2797
        rect.Add(g.NavScoringNoClipRect);
2798
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2799
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2800
2801
    const ImVec2 pos = window->DC.CursorPos;
2802
    int start = (int)((rect.Min.y - pos.y) / items_height);
2803
    int end = (int)((rect.Max.y - pos.y) / items_height);
2804
2805
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2806
    // FIXME: Verify this works with tabbing
2807
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2808
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2809
        start--;
2810
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2811
        end++;
2812
2813
    start = ImClamp(start, 0, items_count);
2814
    end = ImClamp(end + 1, start, items_count);
2815
    *out_items_display_start = start;
2816
    *out_items_display_end = end;
2817
}
2818
#endif
2819
2820
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2821
0
{
2822
0
    if (ranges.Size - offset <= 1)
2823
0
        return;
2824
2825
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2826
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2827
0
        for (int i = offset; i < sort_end + offset; ++i)
2828
0
            if (ranges[i].Min > ranges[i + 1].Min)
2829
0
                ImSwap(ranges[i], ranges[i + 1]);
2830
2831
    // Now fuse ranges together as much as possible.
2832
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2833
0
    {
2834
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2835
0
        if (ranges[i - 1].Max < ranges[i].Min)
2836
0
            continue;
2837
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2838
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2839
0
        ranges.erase(ranges.Data + i);
2840
0
        i--;
2841
0
    }
2842
0
}
2843
2844
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2845
0
{
2846
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2847
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2848
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2849
0
    ImGuiContext& g = *GImGui;
2850
0
    ImGuiWindow* window = g.CurrentWindow;
2851
0
    float off_y = pos_y - window->DC.CursorPos.y;
2852
0
    window->DC.CursorPos.y = pos_y;
2853
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2854
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2855
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2856
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2857
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2858
0
    if (ImGuiTable* table = g.CurrentTable)
2859
0
    {
2860
0
        if (table->IsInsideRow)
2861
0
            ImGui::TableEndRow(table);
2862
0
        table->RowPosY2 = window->DC.CursorPos.y;
2863
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2864
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2865
0
        table->RowBgColorCounter += row_increase;
2866
0
    }
2867
0
}
2868
2869
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2870
0
{
2871
    // StartPosY starts from ItemsFrozen hence the subtraction
2872
    // Perform the add and multiply with double to allow seeking through larger ranges
2873
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2874
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2875
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2876
0
}
2877
2878
ImGuiListClipper::ImGuiListClipper()
2879
0
{
2880
0
    memset(this, 0, sizeof(*this));
2881
0
}
2882
2883
ImGuiListClipper::~ImGuiListClipper()
2884
0
{
2885
0
    End();
2886
0
}
2887
2888
void ImGuiListClipper::Begin(int items_count, float items_height)
2889
0
{
2890
0
    if (Ctx == NULL)
2891
0
        Ctx = ImGui::GetCurrentContext();
2892
2893
0
    ImGuiContext& g = *Ctx;
2894
0
    ImGuiWindow* window = g.CurrentWindow;
2895
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2896
2897
0
    if (ImGuiTable* table = g.CurrentTable)
2898
0
        if (table->IsInsideRow)
2899
0
            ImGui::TableEndRow(table);
2900
2901
0
    StartPosY = window->DC.CursorPos.y;
2902
0
    ItemsHeight = items_height;
2903
0
    ItemsCount = items_count;
2904
0
    DisplayStart = -1;
2905
0
    DisplayEnd = 0;
2906
2907
    // Acquire temporary buffer
2908
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2909
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2910
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2911
0
    data->Reset(this);
2912
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2913
0
    TempData = data;
2914
0
}
2915
2916
void ImGuiListClipper::End()
2917
0
{
2918
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2919
0
    {
2920
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2921
0
        ImGuiContext& g = *Ctx;
2922
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2923
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2924
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2925
2926
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2927
0
        IM_ASSERT(data->ListClipper == this);
2928
0
        data->StepNo = data->Ranges.Size;
2929
0
        if (--g.ClipperTempDataStacked > 0)
2930
0
        {
2931
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2932
0
            data->ListClipper->TempData = data;
2933
0
        }
2934
0
        TempData = NULL;
2935
0
    }
2936
0
    ItemsCount = -1;
2937
0
}
2938
2939
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2940
0
{
2941
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2942
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2943
0
    IM_ASSERT(item_begin <= item_end);
2944
0
    if (item_begin < item_end)
2945
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2946
0
}
2947
2948
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2949
0
{
2950
0
    ImGuiContext& g = *clipper->Ctx;
2951
0
    ImGuiWindow* window = g.CurrentWindow;
2952
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2953
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2954
2955
0
    ImGuiTable* table = g.CurrentTable;
2956
0
    if (table && table->IsInsideRow)
2957
0
        ImGui::TableEndRow(table);
2958
2959
    // No items
2960
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2961
0
        return false;
2962
2963
    // While we are in frozen row state, keep displaying items one by one, unclipped
2964
    // FIXME: Could be stored as a table-agnostic state.
2965
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2966
0
    {
2967
0
        clipper->DisplayStart = data->ItemsFrozen;
2968
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2969
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2970
0
            data->ItemsFrozen++;
2971
0
        return true;
2972
0
    }
2973
2974
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2975
0
    bool calc_clipping = false;
2976
0
    if (data->StepNo == 0)
2977
0
    {
2978
0
        clipper->StartPosY = window->DC.CursorPos.y;
2979
0
        if (clipper->ItemsHeight <= 0.0f)
2980
0
        {
2981
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2982
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2983
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2984
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2985
0
            data->StepNo = 1;
2986
0
            return true;
2987
0
        }
2988
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2989
0
    }
2990
2991
    // Step 1: Let the clipper infer height from first range
2992
0
    if (clipper->ItemsHeight <= 0.0f)
2993
0
    {
2994
0
        IM_ASSERT(data->StepNo == 1);
2995
0
        if (table)
2996
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2997
2998
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2999
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3000
0
        if (affected_by_floating_point_precision)
3001
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3002
3003
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3004
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3005
0
    }
3006
3007
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3008
0
    const int already_submitted = clipper->DisplayEnd;
3009
0
    if (calc_clipping)
3010
0
    {
3011
0
        if (g.LogEnabled)
3012
0
        {
3013
            // If logging is active, do not perform any clipping
3014
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3015
0
        }
3016
0
        else
3017
0
        {
3018
            // Add range selected to be included for navigation
3019
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3020
0
            if (is_nav_request)
3021
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3022
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3023
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3024
3025
            // Add focused/active item
3026
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3027
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3028
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3029
3030
            // Add visible range
3031
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3032
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3033
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3034
0
        }
3035
3036
        // Convert position ranges to item index ranges
3037
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3038
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3039
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3040
0
        for (ImGuiListClipperRange& range : data->Ranges)
3041
0
            if (range.PosToIndexConvert)
3042
0
            {
3043
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3044
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3045
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3046
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3047
0
                range.PosToIndexConvert = false;
3048
0
            }
3049
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3050
0
    }
3051
3052
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3053
0
    while (data->StepNo < data->Ranges.Size)
3054
0
    {
3055
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3056
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3057
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3058
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3059
0
        data->StepNo++;
3060
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3061
0
            continue;
3062
0
        return true;
3063
0
    }
3064
3065
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3066
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3067
0
    if (clipper->ItemsCount < INT_MAX)
3068
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3069
3070
0
    return false;
3071
0
}
3072
3073
bool ImGuiListClipper::Step()
3074
0
{
3075
0
    ImGuiContext& g = *Ctx;
3076
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3077
0
    bool ret = ImGuiListClipper_StepInternal(this);
3078
0
    if (ret && (DisplayStart == DisplayEnd))
3079
0
        ret = false;
3080
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3081
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3082
0
    if (need_items_height && ItemsHeight > 0.0f)
3083
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3084
0
    if (ret)
3085
0
    {
3086
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3087
0
    }
3088
0
    else
3089
0
    {
3090
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3091
0
        End();
3092
0
    }
3093
0
    return ret;
3094
0
}
3095
3096
//-----------------------------------------------------------------------------
3097
// [SECTION] STYLING
3098
//-----------------------------------------------------------------------------
3099
3100
ImGuiStyle& ImGui::GetStyle()
3101
129k
{
3102
129k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3103
129k
    return GImGui->Style;
3104
129k
}
3105
3106
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3107
920k
{
3108
920k
    ImGuiStyle& style = GImGui->Style;
3109
920k
    ImVec4 c = style.Colors[idx];
3110
920k
    c.w *= style.Alpha * alpha_mul;
3111
920k
    return ColorConvertFloat4ToU32(c);
3112
920k
}
3113
3114
ImU32 ImGui::GetColorU32(const ImVec4& col)
3115
0
{
3116
0
    ImGuiStyle& style = GImGui->Style;
3117
0
    ImVec4 c = col;
3118
0
    c.w *= style.Alpha;
3119
0
    return ColorConvertFloat4ToU32(c);
3120
0
}
3121
3122
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3123
0
{
3124
0
    ImGuiStyle& style = GImGui->Style;
3125
0
    return style.Colors[idx];
3126
0
}
3127
3128
ImU32 ImGui::GetColorU32(ImU32 col)
3129
0
{
3130
0
    ImGuiStyle& style = GImGui->Style;
3131
0
    if (style.Alpha >= 1.0f)
3132
0
        return col;
3133
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3134
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3135
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3136
0
}
3137
3138
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3139
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3140
0
{
3141
0
    ImGuiContext& g = *GImGui;
3142
0
    ImGuiColorMod backup;
3143
0
    backup.Col = idx;
3144
0
    backup.BackupValue = g.Style.Colors[idx];
3145
0
    g.ColorStack.push_back(backup);
3146
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3147
0
}
3148
3149
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3150
54.1k
{
3151
54.1k
    ImGuiContext& g = *GImGui;
3152
54.1k
    ImGuiColorMod backup;
3153
54.1k
    backup.Col = idx;
3154
54.1k
    backup.BackupValue = g.Style.Colors[idx];
3155
54.1k
    g.ColorStack.push_back(backup);
3156
54.1k
    g.Style.Colors[idx] = col;
3157
54.1k
}
3158
3159
void ImGui::PopStyleColor(int count)
3160
54.1k
{
3161
54.1k
    ImGuiContext& g = *GImGui;
3162
54.1k
    if (g.ColorStack.Size < count)
3163
0
    {
3164
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3165
0
        count = g.ColorStack.Size;
3166
0
    }
3167
108k
    while (count > 0)
3168
54.1k
    {
3169
54.1k
        ImGuiColorMod& backup = g.ColorStack.back();
3170
54.1k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3171
54.1k
        g.ColorStack.pop_back();
3172
54.1k
        count--;
3173
54.1k
    }
3174
54.1k
}
3175
3176
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3177
{
3178
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3179
};
3180
3181
static const ImGuiDataVarInfo GStyleVarInfo[] =
3182
{
3183
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3184
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3185
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3186
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3187
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3188
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3189
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3190
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3191
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3192
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3193
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3194
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3195
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3196
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3197
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3198
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3199
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3200
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3201
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3202
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3203
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3204
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3205
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3206
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabBarBorderSize) },    // ImGuiStyleVar_TabBarBorderSize
3207
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3208
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3209
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3210
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3211
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3212
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DockingSeparatorSize) },   // ImGuiStyleVar_DockingSeparatorSize
3213
};
3214
3215
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3216
108k
{
3217
108k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3218
108k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3219
108k
    return &GStyleVarInfo[idx];
3220
108k
}
3221
3222
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3223
0
{
3224
0
    ImGuiContext& g = *GImGui;
3225
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3226
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3227
0
    {
3228
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3229
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3230
0
        *pvar = val;
3231
0
        return;
3232
0
    }
3233
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3234
0
}
3235
3236
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3237
54.1k
{
3238
54.1k
    ImGuiContext& g = *GImGui;
3239
54.1k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3240
54.1k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3241
54.1k
    {
3242
54.1k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3243
54.1k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3244
54.1k
        *pvar = val;
3245
54.1k
        return;
3246
54.1k
    }
3247
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3248
0
}
3249
3250
void ImGui::PopStyleVar(int count)
3251
54.1k
{
3252
54.1k
    ImGuiContext& g = *GImGui;
3253
54.1k
    if (g.StyleVarStack.Size < count)
3254
0
    {
3255
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3256
0
        count = g.StyleVarStack.Size;
3257
0
    }
3258
108k
    while (count > 0)
3259
54.1k
    {
3260
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3261
54.1k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3262
54.1k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3263
54.1k
        void* data = info->GetVarPtr(&g.Style);
3264
54.1k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3265
54.1k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3266
54.1k
        g.StyleVarStack.pop_back();
3267
54.1k
        count--;
3268
54.1k
    }
3269
54.1k
}
3270
3271
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3272
0
{
3273
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3274
0
    switch (idx)
3275
0
    {
3276
0
    case ImGuiCol_Text: return "Text";
3277
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3278
0
    case ImGuiCol_WindowBg: return "WindowBg";
3279
0
    case ImGuiCol_ChildBg: return "ChildBg";
3280
0
    case ImGuiCol_PopupBg: return "PopupBg";
3281
0
    case ImGuiCol_Border: return "Border";
3282
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3283
0
    case ImGuiCol_FrameBg: return "FrameBg";
3284
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3285
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3286
0
    case ImGuiCol_TitleBg: return "TitleBg";
3287
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3288
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3289
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3290
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3291
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3292
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3293
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3294
0
    case ImGuiCol_CheckMark: return "CheckMark";
3295
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3296
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3297
0
    case ImGuiCol_Button: return "Button";
3298
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3299
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3300
0
    case ImGuiCol_Header: return "Header";
3301
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3302
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3303
0
    case ImGuiCol_Separator: return "Separator";
3304
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3305
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3306
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3307
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3308
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3309
0
    case ImGuiCol_Tab: return "Tab";
3310
0
    case ImGuiCol_TabHovered: return "TabHovered";
3311
0
    case ImGuiCol_TabActive: return "TabActive";
3312
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3313
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3314
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3315
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3316
0
    case ImGuiCol_PlotLines: return "PlotLines";
3317
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3318
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3319
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3320
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3321
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3322
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3323
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3324
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3325
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3326
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3327
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3328
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3329
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3330
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3331
0
    }
3332
0
    IM_ASSERT(0);
3333
0
    return "Unknown";
3334
0
}
3335
3336
3337
//-----------------------------------------------------------------------------
3338
// [SECTION] RENDER HELPERS
3339
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3340
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3341
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3342
//-----------------------------------------------------------------------------
3343
3344
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3345
216k
{
3346
216k
    const char* text_display_end = text;
3347
216k
    if (!text_end)
3348
216k
        text_end = (const char*)-1;
3349
3350
1.94M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3351
1.73M
        text_display_end++;
3352
216k
    return text_display_end;
3353
216k
}
3354
3355
// Internal ImGui functions to render text
3356
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3357
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3358
0
{
3359
0
    ImGuiContext& g = *GImGui;
3360
0
    ImGuiWindow* window = g.CurrentWindow;
3361
3362
    // Hide anything after a '##' string
3363
0
    const char* text_display_end;
3364
0
    if (hide_text_after_hash)
3365
0
    {
3366
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3367
0
    }
3368
0
    else
3369
0
    {
3370
0
        if (!text_end)
3371
0
            text_end = text + strlen(text); // FIXME-OPT
3372
0
        text_display_end = text_end;
3373
0
    }
3374
3375
0
    if (text != text_display_end)
3376
0
    {
3377
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3378
0
        if (g.LogEnabled)
3379
0
            LogRenderedText(&pos, text, text_display_end);
3380
0
    }
3381
0
}
3382
3383
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3384
0
{
3385
0
    ImGuiContext& g = *GImGui;
3386
0
    ImGuiWindow* window = g.CurrentWindow;
3387
3388
0
    if (!text_end)
3389
0
        text_end = text + strlen(text); // FIXME-OPT
3390
3391
0
    if (text != text_end)
3392
0
    {
3393
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3394
0
        if (g.LogEnabled)
3395
0
            LogRenderedText(&pos, text, text_end);
3396
0
    }
3397
0
}
3398
3399
// Default clip_rect uses (pos_min,pos_max)
3400
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3401
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3402
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3403
// better advantage of the render function taking size into account for coarse clipping.
3404
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3405
108k
{
3406
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3407
108k
    ImVec2 pos = pos_min;
3408
108k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3409
3410
108k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3411
108k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3412
108k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3413
108k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3414
108k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3415
3416
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3417
108k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3418
108k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3419
3420
    // Render
3421
108k
    if (need_clipping)
3422
54.1k
    {
3423
54.1k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3424
54.1k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3425
54.1k
    }
3426
54.1k
    else
3427
54.1k
    {
3428
54.1k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3429
54.1k
    }
3430
108k
}
3431
3432
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3433
108k
{
3434
    // Hide anything after a '##' string
3435
108k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3436
108k
    const int text_len = (int)(text_display_end - text);
3437
108k
    if (text_len == 0)
3438
0
        return;
3439
3440
108k
    ImGuiContext& g = *GImGui;
3441
108k
    ImGuiWindow* window = g.CurrentWindow;
3442
108k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3443
108k
    if (g.LogEnabled)
3444
0
        LogRenderedText(&pos_min, text, text_display_end);
3445
108k
}
3446
3447
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3448
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3449
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3450
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3451
0
{
3452
0
    ImGuiContext& g = *GImGui;
3453
0
    if (text_end_full == NULL)
3454
0
        text_end_full = FindRenderedTextEnd(text);
3455
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3456
3457
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3458
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3459
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3460
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3461
0
    if (text_size.x > pos_max.x - pos_min.x)
3462
0
    {
3463
        // Hello wo...
3464
        // |       |   |
3465
        // min   max   ellipsis_max
3466
        //          <-> this is generally some padding value
3467
3468
0
        const ImFont* font = draw_list->_Data->Font;
3469
0
        const float font_size = draw_list->_Data->FontSize;
3470
0
        const float font_scale = font_size / font->FontSize;
3471
0
        const char* text_end_ellipsis = NULL;
3472
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3473
3474
        // We can now claim the space between pos_max.x and ellipsis_max.x
3475
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3476
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3477
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3478
0
        {
3479
            // Always display at least 1 character if there's no room for character + ellipsis
3480
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3481
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3482
0
        }
3483
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3484
0
        {
3485
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3486
0
            text_end_ellipsis--;
3487
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3488
0
        }
3489
3490
        // Render text, render ellipsis
3491
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3492
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3493
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3494
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3495
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3496
0
    }
3497
0
    else
3498
0
    {
3499
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3500
0
    }
3501
3502
0
    if (g.LogEnabled)
3503
0
        LogRenderedText(&pos_min, text, text_end_full);
3504
0
}
3505
3506
// Render a rectangle shaped with optional rounding and borders
3507
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3508
3.12k
{
3509
3.12k
    ImGuiContext& g = *GImGui;
3510
3.12k
    ImGuiWindow* window = g.CurrentWindow;
3511
3.12k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3512
3.12k
    const float border_size = g.Style.FrameBorderSize;
3513
3.12k
    if (border && border_size > 0.0f)
3514
3.12k
    {
3515
3.12k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3516
3.12k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3517
3.12k
    }
3518
3.12k
}
3519
3520
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3521
0
{
3522
0
    ImGuiContext& g = *GImGui;
3523
0
    ImGuiWindow* window = g.CurrentWindow;
3524
0
    const float border_size = g.Style.FrameBorderSize;
3525
0
    if (border_size > 0.0f)
3526
0
    {
3527
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3528
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3529
0
    }
3530
0
}
3531
3532
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3533
87.5k
{
3534
87.5k
    ImGuiContext& g = *GImGui;
3535
87.5k
    if (id != g.NavId)
3536
45.0k
        return;
3537
42.4k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3538
528
        return;
3539
41.9k
    ImGuiWindow* window = g.CurrentWindow;
3540
41.9k
    if (window->DC.NavHideHighlightOneFrame)
3541
0
        return;
3542
3543
41.9k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3544
41.9k
    ImRect display_rect = bb;
3545
41.9k
    display_rect.ClipWith(window->ClipRect);
3546
41.9k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3547
2.99k
    {
3548
2.99k
        const float THICKNESS = 2.0f;
3549
2.99k
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3550
2.99k
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3551
2.99k
        bool fully_visible = window->ClipRect.Contains(display_rect);
3552
2.99k
        if (!fully_visible)
3553
89
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3554
2.99k
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3555
2.99k
        if (!fully_visible)
3556
89
            window->DrawList->PopClipRect();
3557
2.99k
    }
3558
41.9k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3559
38.9k
    {
3560
38.9k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3561
38.9k
    }
3562
41.9k
}
3563
3564
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3565
0
{
3566
0
    ImGuiContext& g = *GImGui;
3567
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3568
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3569
0
    for (ImGuiViewportP* viewport : g.Viewports)
3570
0
    {
3571
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3572
0
        ImVec2 offset, size, uv[4];
3573
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3574
0
            continue;
3575
0
        const ImVec2 pos = base_pos - offset;
3576
0
        const float scale = base_scale * viewport->DpiScale;
3577
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3578
0
            continue;
3579
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3580
0
        ImTextureID tex_id = font_atlas->TexID;
3581
0
        draw_list->PushTextureID(tex_id);
3582
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3583
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3584
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3585
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3586
0
        draw_list->PopTextureID();
3587
0
    }
3588
0
}
3589
3590
//-----------------------------------------------------------------------------
3591
// [SECTION] INITIALIZATION, SHUTDOWN
3592
//-----------------------------------------------------------------------------
3593
3594
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3595
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3596
ImGuiContext* ImGui::GetCurrentContext()
3597
1
{
3598
1
    return GImGui;
3599
1
}
3600
3601
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3602
1
{
3603
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3604
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3605
#else
3606
1
    GImGui = ctx;
3607
1
#endif
3608
1
}
3609
3610
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3611
0
{
3612
0
    GImAllocatorAllocFunc = alloc_func;
3613
0
    GImAllocatorFreeFunc = free_func;
3614
0
    GImAllocatorUserData = user_data;
3615
0
}
3616
3617
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3618
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3619
0
{
3620
0
    *p_alloc_func = GImAllocatorAllocFunc;
3621
0
    *p_free_func = GImAllocatorFreeFunc;
3622
0
    *p_user_data = GImAllocatorUserData;
3623
0
}
3624
3625
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3626
1
{
3627
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3628
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3629
1
    SetCurrentContext(ctx);
3630
1
    Initialize();
3631
1
    if (prev_ctx != NULL)
3632
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3633
1
    return ctx;
3634
1
}
3635
3636
void ImGui::DestroyContext(ImGuiContext* ctx)
3637
0
{
3638
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3639
0
    if (ctx == NULL) //-V1051
3640
0
        ctx = prev_ctx;
3641
0
    SetCurrentContext(ctx);
3642
0
    Shutdown();
3643
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3644
0
    IM_DELETE(ctx);
3645
0
}
3646
3647
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3648
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3649
{
3650
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3651
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3652
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3653
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3654
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3655
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3656
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3657
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3658
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3659
    { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window."},
3660
};
3661
3662
void ImGui::Initialize()
3663
1
{
3664
1
    ImGuiContext& g = *GImGui;
3665
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3666
3667
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3668
1
    {
3669
1
        ImGuiSettingsHandler ini_handler;
3670
1
        ini_handler.TypeName = "Window";
3671
1
        ini_handler.TypeHash = ImHashStr("Window");
3672
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3673
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3674
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3675
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3676
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3677
1
        AddSettingsHandler(&ini_handler);
3678
1
    }
3679
1
    TableSettingsAddSettingsHandler();
3680
3681
    // Setup default localization table
3682
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3683
3684
    // Setup default platform clipboard/IME handlers.
3685
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3686
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3687
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3688
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3689
3690
    // Create default viewport
3691
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3692
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3693
1
    viewport->Idx = 0;
3694
1
    viewport->PlatformWindowCreated = true;
3695
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3696
1
    g.Viewports.push_back(viewport);
3697
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3698
1
    g.ViewportCreatedCount++;
3699
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3700
3701
1
#ifdef IMGUI_HAS_DOCK
3702
    // Initialize Docking
3703
1
    DockContextInitialize(&g);
3704
1
#endif
3705
3706
1
    g.Initialized = true;
3707
1
}
3708
3709
// This function is merely here to free heap allocations.
3710
void ImGui::Shutdown()
3711
0
{
3712
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3713
0
    ImGuiContext& g = *GImGui;
3714
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3715
0
    {
3716
0
        g.IO.Fonts->Locked = false;
3717
0
        IM_DELETE(g.IO.Fonts);
3718
0
    }
3719
0
    g.IO.Fonts = NULL;
3720
0
    g.DrawListSharedData.TempBuffer.clear();
3721
3722
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3723
0
    if (!g.Initialized)
3724
0
        return;
3725
3726
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3727
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3728
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3729
3730
    // Destroy platform windows
3731
0
    DestroyPlatformWindows();
3732
3733
    // Shutdown extensions
3734
0
    DockContextShutdown(&g);
3735
3736
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3737
3738
    // Clear everything else
3739
0
    g.Windows.clear_delete();
3740
0
    g.WindowsFocusOrder.clear();
3741
0
    g.WindowsTempSortBuffer.clear();
3742
0
    g.CurrentWindow = NULL;
3743
0
    g.CurrentWindowStack.clear();
3744
0
    g.WindowsById.Clear();
3745
0
    g.NavWindow = NULL;
3746
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3747
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3748
0
    g.MovingWindow = NULL;
3749
3750
0
    g.KeysRoutingTable.Clear();
3751
3752
0
    g.ColorStack.clear();
3753
0
    g.StyleVarStack.clear();
3754
0
    g.FontStack.clear();
3755
0
    g.OpenPopupStack.clear();
3756
0
    g.BeginPopupStack.clear();
3757
0
    g.NavTreeNodeStack.clear();
3758
3759
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3760
0
    g.Viewports.clear_delete();
3761
3762
0
    g.TabBars.Clear();
3763
0
    g.CurrentTabBarStack.clear();
3764
0
    g.ShrinkWidthBuffer.clear();
3765
3766
0
    g.ClipperTempData.clear_destruct();
3767
3768
0
    g.Tables.Clear();
3769
0
    g.TablesTempData.clear_destruct();
3770
0
    g.DrawChannelsTempMergeBuffer.clear();
3771
3772
0
    g.ClipboardHandlerData.clear();
3773
0
    g.MenusIdSubmittedThisFrame.clear();
3774
0
    g.InputTextState.ClearFreeMemory();
3775
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3776
3777
0
    g.SettingsWindows.clear();
3778
0
    g.SettingsHandlers.clear();
3779
3780
0
    if (g.LogFile)
3781
0
    {
3782
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3783
0
        if (g.LogFile != stdout)
3784
0
#endif
3785
0
            ImFileClose(g.LogFile);
3786
0
        g.LogFile = NULL;
3787
0
    }
3788
0
    g.LogBuffer.clear();
3789
0
    g.DebugLogBuf.clear();
3790
0
    g.DebugLogIndex.clear();
3791
3792
0
    g.Initialized = false;
3793
0
}
3794
3795
// No specific ordering/dependency support, will see as needed
3796
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3797
0
{
3798
0
    ImGuiContext& g = *ctx;
3799
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3800
0
    g.Hooks.push_back(*hook);
3801
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3802
0
    return g.HookIdNext;
3803
0
}
3804
3805
// Deferred removal, avoiding issue with changing vector while iterating it
3806
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3807
0
{
3808
0
    ImGuiContext& g = *ctx;
3809
0
    IM_ASSERT(hook_id != 0);
3810
0
    for (ImGuiContextHook& hook : g.Hooks)
3811
0
        if (hook.HookId == hook_id)
3812
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3813
0
}
3814
3815
// Call context hooks (used by e.g. test engine)
3816
// We assume a small number of hooks so all stored in same array
3817
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3818
324k
{
3819
324k
    ImGuiContext& g = *ctx;
3820
324k
    for (ImGuiContextHook& hook : g.Hooks)
3821
0
        if (hook.Type == hook_type)
3822
0
            hook.Callback(&g, &hook);
3823
324k
}
3824
3825
3826
//-----------------------------------------------------------------------------
3827
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3828
//-----------------------------------------------------------------------------
3829
3830
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3831
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3832
3
{
3833
3
    memset(this, 0, sizeof(*this));
3834
3
    Ctx = ctx;
3835
3
    Name = ImStrdup(name);
3836
3
    NameBufLen = (int)strlen(name) + 1;
3837
3
    ID = ImHashStr(name);
3838
3
    IDStack.push_back(ID);
3839
3
    ViewportAllowPlatformMonitorExtend = -1;
3840
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3841
3
    MoveId = GetID("#MOVE");
3842
3
    TabId = GetID("#TAB");
3843
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3844
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3845
3
    AutoFitFramesX = AutoFitFramesY = -1;
3846
3
    AutoPosLastDirection = ImGuiDir_None;
3847
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3848
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3849
3
    LastFrameActive = -1;
3850
3
    LastFrameJustFocused = -1;
3851
3
    LastTimeActive = -1.0f;
3852
3
    FontWindowScale = FontDpiScale = 1.0f;
3853
3
    SettingsOffset = -1;
3854
3
    DockOrder = -1;
3855
3
    DrawList = &DrawListInst;
3856
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3857
3
    DrawList->_OwnerName = Name;
3858
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3859
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3860
3
}
3861
3862
ImGuiWindow::~ImGuiWindow()
3863
0
{
3864
0
    IM_ASSERT(DrawList == &DrawListInst);
3865
0
    IM_DELETE(Name);
3866
0
    ColumnsStorage.clear_destruct();
3867
0
}
3868
3869
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3870
313k
{
3871
313k
    ImGuiID seed = IDStack.back();
3872
313k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3873
313k
    ImGuiContext& g = *Ctx;
3874
313k
    if (g.DebugHookIdInfo == id)
3875
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3876
313k
    return id;
3877
313k
}
3878
3879
ImGuiID ImGuiWindow::GetID(const void* ptr)
3880
0
{
3881
0
    ImGuiID seed = IDStack.back();
3882
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3883
0
    ImGuiContext& g = *Ctx;
3884
0
    if (g.DebugHookIdInfo == id)
3885
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3886
0
    return id;
3887
0
}
3888
3889
ImGuiID ImGuiWindow::GetID(int n)
3890
51.0k
{
3891
51.0k
    ImGuiID seed = IDStack.back();
3892
51.0k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3893
51.0k
    ImGuiContext& g = *Ctx;
3894
51.0k
    if (g.DebugHookIdInfo == id)
3895
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3896
51.0k
    return id;
3897
51.0k
}
3898
3899
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3900
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3901
0
{
3902
0
    ImGuiID seed = IDStack.back();
3903
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3904
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3905
0
    return id;
3906
0
}
3907
3908
static void SetCurrentWindow(ImGuiWindow* window)
3909
318k
{
3910
318k
    ImGuiContext& g = *GImGui;
3911
318k
    g.CurrentWindow = window;
3912
318k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3913
318k
    if (window)
3914
264k
    {
3915
264k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3916
264k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3917
264k
    }
3918
318k
}
3919
3920
void ImGui::GcCompactTransientMiscBuffers()
3921
0
{
3922
0
    ImGuiContext& g = *GImGui;
3923
0
    g.ItemFlagsStack.clear();
3924
0
    g.GroupStack.clear();
3925
0
    TableGcCompactSettings();
3926
0
}
3927
3928
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3929
// Not freed:
3930
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3931
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3932
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3933
0
{
3934
0
    window->MemoryCompacted = true;
3935
0
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3936
0
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3937
0
    window->IDStack.clear();
3938
0
    window->DrawList->_ClearFreeMemory();
3939
0
    window->DC.ChildWindows.clear();
3940
0
    window->DC.ItemWidthStack.clear();
3941
0
    window->DC.TextWrapPosStack.clear();
3942
0
}
3943
3944
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3945
0
{
3946
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3947
    // The other buffers tends to amortize much faster.
3948
0
    window->MemoryCompacted = false;
3949
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3950
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3951
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3952
0
}
3953
3954
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3955
433
{
3956
433
    ImGuiContext& g = *GImGui;
3957
3958
    // Clear previous active id
3959
433
    if (g.ActiveId != 0)
3960
27
    {
3961
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3962
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3963
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3964
27
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3965
0
        {
3966
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3967
0
            g.MovingWindow = NULL;
3968
0
        }
3969
3970
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3971
        // but since this is currently quite an exception we'll leave it as is.
3972
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3973
27
        if (g.InputTextState.ID == g.ActiveId)
3974
0
            InputTextDeactivateHook(g.ActiveId);
3975
27
    }
3976
3977
    // Set active id
3978
433
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3979
433
    if (g.ActiveIdIsJustActivated)
3980
54
    {
3981
54
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3982
54
        g.ActiveIdTimer = 0.0f;
3983
54
        g.ActiveIdHasBeenPressedBefore = false;
3984
54
        g.ActiveIdHasBeenEditedBefore = false;
3985
54
        g.ActiveIdMouseButton = -1;
3986
54
        if (id != 0)
3987
27
        {
3988
27
            g.LastActiveId = id;
3989
27
            g.LastActiveIdTimer = 0.0f;
3990
27
        }
3991
54
    }
3992
433
    g.ActiveId = id;
3993
433
    g.ActiveIdAllowOverlap = false;
3994
433
    g.ActiveIdNoClearOnFocusLoss = false;
3995
433
    g.ActiveIdWindow = window;
3996
433
    g.ActiveIdHasBeenEditedThisFrame = false;
3997
433
    if (id)
3998
27
    {
3999
27
        g.ActiveIdIsAlive = id;
4000
27
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4001
27
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4002
27
    }
4003
4004
    // Clear declaration of inputs claimed by the widget
4005
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4006
433
    g.ActiveIdUsingNavDirMask = 0x00;
4007
433
    g.ActiveIdUsingAllKeyboardKeys = false;
4008
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4009
    g.ActiveIdUsingNavInputMask = 0x00;
4010
#endif
4011
433
}
4012
4013
void ImGui::ClearActiveID()
4014
406
{
4015
406
    SetActiveID(0, NULL); // g.ActiveId = 0;
4016
406
}
4017
4018
void ImGui::SetHoveredID(ImGuiID id)
4019
100
{
4020
100
    ImGuiContext& g = *GImGui;
4021
100
    g.HoveredId = id;
4022
100
    g.HoveredIdAllowOverlap = false;
4023
100
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4024
43
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4025
100
}
4026
4027
ImGuiID ImGui::GetHoveredID()
4028
0
{
4029
0
    ImGuiContext& g = *GImGui;
4030
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4031
0
}
4032
4033
// This is called by ItemAdd().
4034
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
4035
void ImGui::KeepAliveID(ImGuiID id)
4036
262k
{
4037
262k
    ImGuiContext& g = *GImGui;
4038
262k
    if (g.ActiveId == id)
4039
45
        g.ActiveIdIsAlive = id;
4040
262k
    if (g.ActiveIdPreviousFrame == id)
4041
45
        g.ActiveIdPreviousFrameIsAlive = true;
4042
262k
}
4043
4044
void ImGui::MarkItemEdited(ImGuiID id)
4045
0
{
4046
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4047
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4048
0
    ImGuiContext& g = *GImGui;
4049
0
    if (g.LockMarkEdited > 0)
4050
0
        return;
4051
0
    if (g.ActiveId == id || g.ActiveId == 0)
4052
0
    {
4053
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4054
0
        g.ActiveIdHasBeenEditedBefore = true;
4055
0
    }
4056
4057
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4058
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4059
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4060
4061
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4062
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4063
0
}
4064
4065
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4066
101
{
4067
    // An active popup disable hovering on other windows (apart from its own children)
4068
    // FIXME-OPT: This could be cached/stored within the window.
4069
101
    ImGuiContext& g = *GImGui;
4070
101
    if (g.NavWindow)
4071
26
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4072
26
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4073
0
            {
4074
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4075
                // NB: The 'else' is important because Modal windows are also Popups.
4076
0
                bool want_inhibit = false;
4077
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4078
0
                    want_inhibit = true;
4079
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4080
0
                    want_inhibit = true;
4081
4082
                // Inhibit hover unless the window is within the stack of our modal/popup
4083
0
                if (want_inhibit)
4084
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4085
0
                        return false;
4086
0
            }
4087
4088
    // Filter by viewport
4089
101
    if (window->Viewport != g.MouseViewport)
4090
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4091
0
            return false;
4092
4093
101
    return true;
4094
101
}
4095
4096
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4097
0
{
4098
0
    ImGuiContext& g = *GImGui;
4099
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4100
0
        return g.Style.HoverDelayShort;
4101
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4102
0
        return g.Style.HoverDelayNormal;
4103
0
    return 0.0f;
4104
0
}
4105
4106
// This is roughly matching the behavior of internal-facing ItemHoverable()
4107
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4108
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4109
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4110
0
{
4111
0
    ImGuiContext& g = *GImGui;
4112
0
    ImGuiWindow* window = g.CurrentWindow;
4113
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4114
4115
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4116
0
    {
4117
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4118
0
            return false;
4119
0
        if (!IsItemFocused())
4120
0
            return false;
4121
4122
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4123
0
            flags |= g.Style.HoverFlagsForTooltipNav;
4124
0
    }
4125
0
    else
4126
0
    {
4127
        // Test for bounding box overlap, as updated as ItemAdd()
4128
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4129
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4130
0
            return false;
4131
4132
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4133
0
            flags |= g.Style.HoverFlagsForTooltipMouse;
4134
4135
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4136
4137
        // Done with rectangle culling so we can perform heavier checks now
4138
        // Test if we are hovering the right window (our window could be behind another window)
4139
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4140
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4141
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4142
        // the test that has been running for a long while.
4143
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4144
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4145
0
                return false;
4146
4147
        // Test if another item is active (e.g. being dragged)
4148
0
        const ImGuiID id = g.LastItemData.ID;
4149
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4150
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4151
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4152
0
                    return false;
4153
4154
        // Test if interactions on this window are blocked by an active popup or modal.
4155
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4156
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4157
0
            return false;
4158
4159
        // Test if the item is disabled
4160
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4161
0
            return false;
4162
4163
        // Special handling for calling after Begin() which represent the title bar or tab.
4164
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4165
        // will never be overwritten so we need to detect the case.
4166
0
        if (id == window->MoveId && window->WriteAccessed)
4167
0
            return false;
4168
4169
        // Test if using AllowOverlap and overlapped
4170
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4171
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4172
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4173
0
                    return false;
4174
0
    }
4175
4176
    // Handle hover delay
4177
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4178
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4179
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4180
0
    {
4181
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4182
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4183
0
            g.HoverItemDelayTimer = 0.0f;
4184
0
        g.HoverItemDelayId = hover_delay_id;
4185
4186
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4187
        // but once unlocked on a given item we also moving.
4188
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4189
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4190
0
            return false;
4191
4192
0
        if (g.HoverItemDelayTimer < delay)
4193
0
            return false;
4194
0
    }
4195
4196
0
    return true;
4197
0
}
4198
4199
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4200
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4201
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4202
// If you used this in your legacy/custom widgets code:
4203
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4204
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4205
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4206
214k
{
4207
214k
    ImGuiContext& g = *GImGui;
4208
214k
    ImGuiWindow* window = g.CurrentWindow;
4209
214k
    if (g.HoveredWindow != window)
4210
211k
        return false;
4211
2.35k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4212
2.25k
        return false;
4213
4214
100
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4215
0
        return false;
4216
100
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4217
0
        return false;
4218
4219
    // Done with rectangle culling so we can perform heavier checks now.
4220
100
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4221
0
    {
4222
0
        g.HoveredIdDisabled = true;
4223
0
        return false;
4224
0
    }
4225
4226
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4227
    // hover test in widgets code. We could also decide to split this function is two.
4228
100
    if (id != 0)
4229
100
    {
4230
        // Drag source doesn't report as hovered
4231
100
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4232
0
            return false;
4233
4234
100
        SetHoveredID(id);
4235
4236
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4237
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4238
100
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4239
0
        {
4240
0
            g.HoveredIdAllowOverlap = true;
4241
0
            if (g.HoveredIdPreviousFrame != id)
4242
0
                return false;
4243
0
        }
4244
100
    }
4245
4246
    // When disabled we'll return false but still set HoveredId
4247
100
    if (item_flags & ImGuiItemFlags_Disabled)
4248
0
    {
4249
        // Release active id if turning disabled
4250
0
        if (g.ActiveId == id && id != 0)
4251
0
            ClearActiveID();
4252
0
        g.HoveredIdDisabled = true;
4253
0
        return false;
4254
0
    }
4255
4256
100
    if (id != 0)
4257
100
    {
4258
        // [DEBUG] Item Picker tool!
4259
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4260
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4261
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4262
100
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4263
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4264
100
        if (g.DebugItemPickerBreakId == id)
4265
0
            IM_DEBUG_BREAK();
4266
100
    }
4267
4268
100
    if (g.NavDisableMouseHover)
4269
9
        return false;
4270
4271
91
    return true;
4272
100
}
4273
4274
// FIXME: This is inlined/duplicated in ItemAdd()
4275
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4276
0
{
4277
0
    ImGuiContext& g = *GImGui;
4278
0
    ImGuiWindow* window = g.CurrentWindow;
4279
0
    if (!bb.Overlaps(window->ClipRect))
4280
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4281
0
            if (!g.LogEnabled)
4282
0
                return true;
4283
0
    return false;
4284
0
}
4285
4286
// This is also inlined in ItemAdd()
4287
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4288
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4289
159k
{
4290
159k
    ImGuiContext& g = *GImGui;
4291
159k
    g.LastItemData.ID = item_id;
4292
159k
    g.LastItemData.InFlags = in_flags;
4293
159k
    g.LastItemData.StatusFlags = item_flags;
4294
159k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4295
159k
}
4296
4297
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4298
0
{
4299
0
    if (wrap_pos_x < 0.0f)
4300
0
        return 0.0f;
4301
4302
0
    ImGuiContext& g = *GImGui;
4303
0
    ImGuiWindow* window = g.CurrentWindow;
4304
0
    if (wrap_pos_x == 0.0f)
4305
0
    {
4306
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4307
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4308
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4309
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4310
        //else
4311
0
        wrap_pos_x = window->WorkRect.Max.x;
4312
0
    }
4313
0
    else if (wrap_pos_x > 0.0f)
4314
0
    {
4315
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4316
0
    }
4317
4318
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4319
0
}
4320
4321
// IM_ALLOC() == ImGui::MemAlloc()
4322
void* ImGui::MemAlloc(size_t size)
4323
1.22k
{
4324
1.22k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4325
1.22k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4326
1.22k
    if (ImGuiContext* ctx = GImGui)
4327
1.22k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4328
1.22k
#endif
4329
1.22k
    return ptr;
4330
1.22k
}
4331
4332
// IM_FREE() == ImGui::MemFree()
4333
void ImGui::MemFree(void* ptr)
4334
1.17k
{
4335
1.17k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4336
1.17k
    if (ptr != NULL)
4337
1.16k
        if (ImGuiContext* ctx = GImGui)
4338
1.16k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4339
1.17k
#endif
4340
1.17k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4341
1.17k
}
4342
4343
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4344
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4345
2.38k
{
4346
2.38k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4347
2.38k
    IM_UNUSED(ptr);
4348
2.38k
    if (entry->FrameCount != frame_count)
4349
37
    {
4350
37
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4351
37
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4352
37
        entry->FrameCount = frame_count;
4353
37
        entry->AllocCount = entry->FreeCount = 0;
4354
37
    }
4355
2.38k
    if (size != (size_t)-1)
4356
1.22k
    {
4357
1.22k
        entry->AllocCount++;
4358
1.22k
        info->TotalAllocCount++;
4359
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4360
1.22k
    }
4361
1.16k
    else
4362
1.16k
    {
4363
1.16k
        entry->FreeCount++;
4364
1.16k
        info->TotalFreeCount++;
4365
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4366
1.16k
    }
4367
2.38k
}
4368
4369
const char* ImGui::GetClipboardText()
4370
0
{
4371
0
    ImGuiContext& g = *GImGui;
4372
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4373
0
}
4374
4375
void ImGui::SetClipboardText(const char* text)
4376
0
{
4377
0
    ImGuiContext& g = *GImGui;
4378
0
    if (g.IO.SetClipboardTextFn)
4379
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4380
0
}
4381
4382
const char* ImGui::GetVersion()
4383
0
{
4384
0
    return IMGUI_VERSION;
4385
0
}
4386
4387
ImGuiIO& ImGui::GetIO()
4388
185k
{
4389
185k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4390
185k
    return GImGui->IO;
4391
185k
}
4392
4393
ImGuiPlatformIO& ImGui::GetPlatformIO()
4394
0
{
4395
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4396
0
    return GImGui->PlatformIO;
4397
0
}
4398
4399
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4400
ImDrawData* ImGui::GetDrawData()
4401
54.1k
{
4402
54.1k
    ImGuiContext& g = *GImGui;
4403
54.1k
    ImGuiViewportP* viewport = g.Viewports[0];
4404
54.1k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4405
54.1k
}
4406
4407
double ImGui::GetTime()
4408
1
{
4409
1
    return GImGui->Time;
4410
1
}
4411
4412
int ImGui::GetFrameCount()
4413
0
{
4414
0
    return GImGui->FrameCount;
4415
0
}
4416
4417
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4418
0
{
4419
    // Create the draw list on demand, because they are not frequently used for all viewports
4420
0
    ImGuiContext& g = *GImGui;
4421
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4422
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4423
0
    if (draw_list == NULL)
4424
0
    {
4425
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4426
0
        draw_list->_OwnerName = drawlist_name;
4427
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4428
0
    }
4429
4430
    // Our ImDrawList system requires that there is always a command
4431
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4432
0
    {
4433
0
        draw_list->_ResetForNewFrame();
4434
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4435
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4436
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4437
0
    }
4438
0
    return draw_list;
4439
0
}
4440
4441
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4442
0
{
4443
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4444
0
}
4445
4446
ImDrawList* ImGui::GetBackgroundDrawList()
4447
0
{
4448
0
    ImGuiContext& g = *GImGui;
4449
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4450
0
}
4451
4452
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4453
0
{
4454
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4455
0
}
4456
4457
ImDrawList* ImGui::GetForegroundDrawList()
4458
0
{
4459
0
    ImGuiContext& g = *GImGui;
4460
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4461
0
}
4462
4463
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4464
0
{
4465
0
    return &GImGui->DrawListSharedData;
4466
0
}
4467
4468
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4469
10
{
4470
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4471
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4472
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4473
10
    ImGuiContext& g = *GImGui;
4474
10
    FocusWindow(window);
4475
10
    SetActiveID(window->MoveId, window);
4476
10
    g.NavDisableHighlight = true;
4477
10
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4478
10
    g.ActiveIdNoClearOnFocusLoss = true;
4479
10
    SetActiveIdUsingAllKeyboardKeys();
4480
4481
10
    bool can_move_window = true;
4482
10
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4483
0
        can_move_window = false;
4484
10
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4485
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4486
0
            can_move_window = false;
4487
10
    if (can_move_window)
4488
10
        g.MovingWindow = window;
4489
10
}
4490
4491
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4492
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4493
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4494
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4495
0
{
4496
0
    ImGuiContext& g = *GImGui;
4497
0
    bool can_undock_node = false;
4498
0
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4499
0
    {
4500
        // Can undock if:
4501
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4502
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4503
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4504
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4505
0
            if (undock_floating_node || root_node->IsDockSpace())
4506
0
                can_undock_node = true;
4507
0
    }
4508
4509
0
    const bool clicked = IsMouseClicked(0);
4510
0
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4511
0
    if (can_undock_node && dragging)
4512
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4513
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4514
0
        StartMouseMovingWindow(window);
4515
0
}
4516
4517
// Handle mouse moving window
4518
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4519
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4520
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4521
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4522
void ImGui::UpdateMouseMovingWindowNewFrame()
4523
54.1k
{
4524
54.1k
    ImGuiContext& g = *GImGui;
4525
54.1k
    if (g.MovingWindow != NULL)
4526
40
    {
4527
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4528
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4529
40
        KeepAliveID(g.ActiveId);
4530
40
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4531
40
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4532
4533
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4534
40
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4535
40
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4536
30
        {
4537
30
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4538
30
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4539
7
            {
4540
7
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4541
7
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4542
0
                {
4543
0
                    moving_window->Viewport->Pos = pos;
4544
0
                    moving_window->Viewport->UpdateWorkRect();
4545
0
                }
4546
7
            }
4547
30
            FocusWindow(g.MovingWindow);
4548
30
        }
4549
10
        else
4550
10
        {
4551
10
            if (!window_disappared)
4552
10
            {
4553
                // Try to merge the window back into the main viewport.
4554
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4555
10
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4556
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4557
4558
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4559
10
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4560
10
                    g.MouseViewport = moving_window->Viewport;
4561
4562
                // Clear the NoInput window flag set by the Viewport system
4563
10
                if (moving_window->Viewport)
4564
10
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4565
10
            }
4566
4567
10
            g.MovingWindow = NULL;
4568
10
            ClearActiveID();
4569
10
        }
4570
40
    }
4571
54.0k
    else
4572
54.0k
    {
4573
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4574
54.0k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4575
0
        {
4576
0
            KeepAliveID(g.ActiveId);
4577
0
            if (!g.IO.MouseDown[0])
4578
0
                ClearActiveID();
4579
0
        }
4580
54.0k
    }
4581
54.1k
}
4582
4583
// Initiate moving window when clicking on empty space or title bar.
4584
// Handle left-click and right-click focus.
4585
void ImGui::UpdateMouseMovingWindowEndFrame()
4586
54.1k
{
4587
54.1k
    ImGuiContext& g = *GImGui;
4588
54.1k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4589
141
        return;
4590
4591
    // Unless we just made a window/popup appear
4592
53.9k
    if (g.NavWindow && g.NavWindow->Appearing)
4593
2
        return;
4594
4595
    // Click on empty space to focus window and start moving
4596
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4597
53.9k
    if (g.IO.MouseClicked[0])
4598
1.75k
    {
4599
        // Handle the edge case of a popup being closed while clicking in its empty space.
4600
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4601
1.75k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4602
1.75k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4603
4604
1.75k
        if (root_window != NULL && !is_closed_popup)
4605
10
        {
4606
10
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4607
4608
            // Cancel moving if clicked outside of title bar
4609
10
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4610
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4611
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4612
0
                        g.MovingWindow = NULL;
4613
4614
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4615
10
            if (g.HoveredIdDisabled)
4616
0
                g.MovingWindow = NULL;
4617
10
        }
4618
1.74k
        else if (root_window == NULL && g.NavWindow != NULL)
4619
1.24k
        {
4620
            // Clicking on void disable focus
4621
1.24k
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4622
1.24k
        }
4623
1.75k
    }
4624
4625
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4626
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4627
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4628
53.9k
    if (g.IO.MouseClicked[1])
4629
239
    {
4630
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4631
        // This is where we can trim the popup stack.
4632
239
        ImGuiWindow* modal = GetTopMostPopupModal();
4633
239
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4634
239
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4635
239
    }
4636
53.9k
}
4637
4638
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4639
// Need to keep in sync with SetWindowPos()
4640
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4641
0
{
4642
0
    window->Pos += delta;
4643
0
    window->ClipRect.Translate(delta);
4644
0
    window->OuterRectClipped.Translate(delta);
4645
0
    window->InnerRect.Translate(delta);
4646
0
    window->DC.CursorPos += delta;
4647
0
    window->DC.CursorStartPos += delta;
4648
0
    window->DC.CursorMaxPos += delta;
4649
0
    window->DC.IdealMaxPos += delta;
4650
0
}
4651
4652
static void ScaleWindow(ImGuiWindow* window, float scale)
4653
0
{
4654
0
    ImVec2 origin = window->Viewport->Pos;
4655
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4656
0
    window->Size = ImTrunc(window->Size * scale);
4657
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4658
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4659
0
}
4660
4661
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4662
213k
{
4663
213k
    return (window->Active) && (!window->Hidden);
4664
213k
}
4665
4666
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4667
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4668
54.1k
{
4669
54.1k
    ImGuiContext& g = *GImGui;
4670
54.1k
    ImGuiIO& io = g.IO;
4671
54.1k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4672
4673
    // Find the window hovered by mouse:
4674
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4675
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4676
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4677
54.1k
    bool clear_hovered_windows = false;
4678
54.1k
    FindHoveredWindow();
4679
54.1k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4680
4681
    // Modal windows prevents mouse from hovering behind them.
4682
54.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4683
54.1k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4684
0
        clear_hovered_windows = true;
4685
4686
    // Disabled mouse?
4687
54.1k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4688
0
        clear_hovered_windows = true;
4689
4690
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4691
    // won't report hovering nor request capture even while dragging over our windows afterward.
4692
54.1k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4693
54.1k
    const bool has_open_modal = (modal_window != NULL);
4694
54.1k
    int mouse_earliest_down = -1;
4695
54.1k
    bool mouse_any_down = false;
4696
324k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4697
270k
    {
4698
270k
        if (io.MouseClicked[i])
4699
2.76k
        {
4700
2.76k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4701
2.76k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4702
2.76k
        }
4703
270k
        mouse_any_down |= io.MouseDown[i];
4704
270k
        if (io.MouseDown[i])
4705
13.9k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4706
9.47k
                mouse_earliest_down = i;
4707
270k
    }
4708
54.1k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4709
54.1k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4710
4711
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4712
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4713
54.1k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4714
54.1k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4715
8.33k
        clear_hovered_windows = true;
4716
4717
54.1k
    if (clear_hovered_windows)
4718
8.33k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4719
4720
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4721
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4722
54.1k
    if (g.WantCaptureMouseNextFrame != -1)
4723
0
    {
4724
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4725
0
    }
4726
54.1k
    else
4727
54.1k
    {
4728
54.1k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4729
54.1k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4730
54.1k
    }
4731
4732
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4733
54.1k
    if (g.WantCaptureKeyboardNextFrame != -1)
4734
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4735
54.1k
    else
4736
54.1k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4737
54.1k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4738
37.3k
        io.WantCaptureKeyboard = true;
4739
4740
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4741
54.1k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4742
54.1k
}
4743
4744
void ImGui::NewFrame()
4745
54.1k
{
4746
54.1k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4747
54.1k
    ImGuiContext& g = *GImGui;
4748
4749
    // Remove pending delete hooks before frame start.
4750
    // This deferred removal avoid issues of removal while iterating the hook vector
4751
54.1k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4752
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4753
0
            g.Hooks.erase(&g.Hooks[n]);
4754
4755
54.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4756
4757
    // Check and assert for various common IO and Configuration mistakes
4758
54.1k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4759
54.1k
    ErrorCheckNewFrameSanityChecks();
4760
54.1k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4761
4762
    // Load settings on first frame, save settings when modified (after a delay)
4763
54.1k
    UpdateSettings();
4764
4765
54.1k
    g.Time += g.IO.DeltaTime;
4766
54.1k
    g.WithinFrameScope = true;
4767
54.1k
    g.FrameCount += 1;
4768
54.1k
    g.TooltipOverrideCount = 0;
4769
54.1k
    g.WindowsActiveCount = 0;
4770
54.1k
    g.MenusIdSubmittedThisFrame.resize(0);
4771
4772
    // Calculate frame-rate for the user, as a purely luxurious feature
4773
54.1k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4774
54.1k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4775
54.1k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4776
54.1k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4777
54.1k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4778
4779
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4780
54.1k
    g.InputEventsTrail.resize(0);
4781
54.1k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4782
4783
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4784
54.1k
    UpdateViewportsNewFrame();
4785
4786
    // Setup current font and draw list shared data
4787
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4788
54.1k
    g.IO.Fonts->Locked = true;
4789
54.1k
    SetCurrentFont(GetDefaultFont());
4790
54.1k
    IM_ASSERT(g.Font->IsLoaded());
4791
54.1k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4792
54.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4793
54.1k
        virtual_space.Add(viewport->GetMainRect());
4794
54.1k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4795
54.1k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4796
54.1k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4797
54.1k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4798
54.1k
    if (g.Style.AntiAliasedLines)
4799
54.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4800
54.1k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4801
54.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4802
54.1k
    if (g.Style.AntiAliasedFill)
4803
54.1k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4804
54.1k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4805
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4806
4807
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4808
54.1k
    for (ImGuiViewportP* viewport : g.Viewports)
4809
54.1k
    {
4810
54.1k
        viewport->DrawData = NULL;
4811
54.1k
        viewport->DrawDataP.Valid = false;
4812
54.1k
    }
4813
4814
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4815
54.1k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4816
3
        KeepAliveID(g.DragDropPayload.SourceId);
4817
4818
    // Update HoveredId data
4819
54.1k
    if (!g.HoveredIdPreviousFrame)
4820
54.0k
        g.HoveredIdTimer = 0.0f;
4821
54.1k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4822
54.0k
        g.HoveredIdNotActiveTimer = 0.0f;
4823
54.1k
    if (g.HoveredId)
4824
100
        g.HoveredIdTimer += g.IO.DeltaTime;
4825
54.1k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4826
98
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4827
54.1k
    g.HoveredIdPreviousFrame = g.HoveredId;
4828
54.1k
    g.HoveredId = 0;
4829
54.1k
    g.HoveredIdAllowOverlap = false;
4830
54.1k
    g.HoveredIdDisabled = false;
4831
4832
    // Clear ActiveID if the item is not alive anymore.
4833
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4834
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4835
54.1k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4836
0
    {
4837
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4838
0
        ClearActiveID();
4839
0
    }
4840
4841
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4842
54.1k
    if (g.ActiveId)
4843
51
        g.ActiveIdTimer += g.IO.DeltaTime;
4844
54.1k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4845
54.1k
    g.ActiveIdPreviousFrame = g.ActiveId;
4846
54.1k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4847
54.1k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4848
54.1k
    g.ActiveIdIsAlive = 0;
4849
54.1k
    g.ActiveIdHasBeenEditedThisFrame = false;
4850
54.1k
    g.ActiveIdPreviousFrameIsAlive = false;
4851
54.1k
    g.ActiveIdIsJustActivated = false;
4852
54.1k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4853
0
        g.TempInputId = 0;
4854
54.1k
    if (g.ActiveId == 0)
4855
54.0k
    {
4856
54.0k
        g.ActiveIdUsingNavDirMask = 0x00;
4857
54.0k
        g.ActiveIdUsingAllKeyboardKeys = false;
4858
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4859
        g.ActiveIdUsingNavInputMask = 0x00;
4860
#endif
4861
54.0k
    }
4862
4863
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4864
    if (g.ActiveId == 0)
4865
        g.ActiveIdUsingNavInputMask = 0;
4866
    else if (g.ActiveIdUsingNavInputMask != 0)
4867
    {
4868
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4869
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4870
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4871
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4872
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4873
            IM_ASSERT(0); // Other values unsupported
4874
    }
4875
#endif
4876
4877
    // Record when we have been stationary as this state is preserved while over same item.
4878
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4879
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4880
54.1k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4881
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4882
54.1k
    else if (g.HoverItemDelayId == 0)
4883
54.1k
        g.HoverItemUnlockedStationaryId = 0;
4884
54.1k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4885
674
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4886
53.4k
    else if (g.HoveredWindow == NULL)
4887
52.9k
        g.HoverWindowUnlockedStationaryId = 0;
4888
4889
    // Update hover delay for IsItemHovered() with delays and tooltips
4890
54.1k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4891
54.1k
    if (g.HoverItemDelayId != 0)
4892
0
    {
4893
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4894
0
        g.HoverItemDelayClearTimer = 0.0f;
4895
0
        g.HoverItemDelayId = 0;
4896
0
    }
4897
54.1k
    else if (g.HoverItemDelayTimer > 0.0f)
4898
0
    {
4899
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4900
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4901
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4902
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4903
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4904
0
    }
4905
4906
    // Drag and drop
4907
54.1k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4908
54.1k
    g.DragDropAcceptIdCurr = 0;
4909
54.1k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4910
54.1k
    g.DragDropWithinSource = false;
4911
54.1k
    g.DragDropWithinTarget = false;
4912
54.1k
    g.DragDropHoldJustPressedId = 0;
4913
4914
    // Close popups on focus lost (currently wip/opt-in)
4915
    //if (g.IO.AppFocusLost)
4916
    //    ClosePopupsExceptModals();
4917
4918
    // Update keyboard input state
4919
54.1k
    UpdateKeyboardInputs();
4920
4921
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4922
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4923
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4924
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4925
4926
    // Update gamepad/keyboard navigation
4927
54.1k
    NavUpdate();
4928
4929
    // Update mouse input state
4930
54.1k
    UpdateMouseInputs();
4931
4932
    // Undocking
4933
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4934
54.1k
    DockContextNewFrameUpdateUndocking(&g);
4935
4936
    // Find hovered window
4937
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4938
54.1k
    UpdateHoveredWindowAndCaptureFlags();
4939
4940
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4941
54.1k
    UpdateMouseMovingWindowNewFrame();
4942
4943
    // Background darkening/whitening
4944
54.1k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4945
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4946
54.1k
    else
4947
54.1k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4948
4949
54.1k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4950
54.1k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4951
4952
    // Platform IME data: reset for the frame
4953
54.1k
    g.PlatformImeDataPrev = g.PlatformImeData;
4954
54.1k
    g.PlatformImeData.WantVisible = false;
4955
4956
    // Mouse wheel scrolling, scale
4957
54.1k
    UpdateMouseWheel();
4958
4959
    // Mark all windows as not visible and compact unused memory.
4960
54.1k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4961
54.1k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4962
54.1k
    for (ImGuiWindow* window : g.Windows)
4963
162k
    {
4964
162k
        window->WasActive = window->Active;
4965
162k
        window->Active = false;
4966
162k
        window->WriteAccessed = false;
4967
162k
        window->BeginCountPreviousFrame = window->BeginCount;
4968
162k
        window->BeginCount = 0;
4969
4970
        // Garbage collect transient buffers of recently unused windows
4971
162k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4972
0
            GcCompactTransientWindowBuffers(window);
4973
162k
    }
4974
4975
    // Garbage collect transient buffers of recently unused tables
4976
54.1k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4977
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4978
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4979
54.1k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4980
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4981
0
            TableGcCompactTransientBuffers(&table_temp_data);
4982
54.1k
    if (g.GcCompactAll)
4983
0
        GcCompactTransientMiscBuffers();
4984
54.1k
    g.GcCompactAll = false;
4985
4986
    // Closing the focused window restore focus to the first active root window in descending z-order
4987
54.1k
    if (g.NavWindow && !g.NavWindow->WasActive)
4988
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4989
4990
    // No window should be open at the beginning of the frame.
4991
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4992
54.1k
    g.CurrentWindowStack.resize(0);
4993
54.1k
    g.BeginPopupStack.resize(0);
4994
54.1k
    g.ItemFlagsStack.resize(0);
4995
54.1k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4996
54.1k
    g.GroupStack.resize(0);
4997
4998
    // Docking
4999
54.1k
    DockContextNewFrameUpdateDocking(&g);
5000
5001
    // [DEBUG] Update debug features
5002
54.1k
    UpdateDebugToolItemPicker();
5003
54.1k
    UpdateDebugToolStackQueries();
5004
54.1k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5005
0
        g.DebugLocateId = 0;
5006
54.1k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
5007
0
    {
5008
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
5009
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
5010
0
    }
5011
5012
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5013
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5014
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5015
54.1k
    g.WithinFrameScopeWithImplicitWindow = true;
5016
54.1k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5017
54.1k
    Begin("Debug##Default");
5018
54.1k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5019
5020
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5021
    // allowing to validate correct Begin/End behavior in user code.
5022
54.1k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5023
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5024
54.1k
    else
5025
54.1k
        g.DebugBeginReturnValueCullDepth = -1;
5026
5027
54.1k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5028
54.1k
}
5029
5030
// FIXME: Add a more explicit sort order in the window structure.
5031
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5032
0
{
5033
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5034
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5035
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5036
0
        return d;
5037
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5038
0
        return d;
5039
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5040
0
}
5041
5042
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5043
162k
{
5044
162k
    out_sorted_windows->push_back(window);
5045
162k
    if (window->Active)
5046
105k
    {
5047
105k
        int count = window->DC.ChildWindows.Size;
5048
105k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5049
156k
        for (int i = 0; i < count; i++)
5050
51.0k
        {
5051
51.0k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5052
51.0k
            if (child->Active)
5053
51.0k
                AddWindowToSortBuffer(out_sorted_windows, child);
5054
51.0k
        }
5055
105k
    }
5056
162k
}
5057
5058
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5059
105k
{
5060
105k
    ImGuiContext& g = *GImGui;
5061
105k
    ImGuiViewportP* viewport = window->Viewport;
5062
105k
    IM_ASSERT(viewport != NULL);
5063
105k
    g.IO.MetricsRenderWindows++;
5064
105k
    if (window->DrawList->_Splitter._Count > 1)
5065
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5066
105k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5067
105k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5068
51.0k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5069
51.0k
            AddWindowToDrawData(child, layer);
5070
105k
}
5071
5072
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5073
54.1k
{
5074
54.1k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5075
54.1k
}
5076
5077
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5078
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5079
54.1k
{
5080
54.1k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5081
54.1k
}
5082
5083
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5084
54.1k
{
5085
54.1k
    int n = builder->Layers[0]->Size;
5086
54.1k
    int full_size = n;
5087
108k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5088
54.1k
        full_size += builder->Layers[i]->Size;
5089
54.1k
    builder->Layers[0]->resize(full_size);
5090
108k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5091
54.1k
    {
5092
54.1k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5093
54.1k
        if (layer->empty())
5094
54.1k
            continue;
5095
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5096
0
        n += layer->Size;
5097
0
        layer->resize(0);
5098
0
    }
5099
54.1k
}
5100
5101
static void InitViewportDrawData(ImGuiViewportP* viewport)
5102
54.1k
{
5103
54.1k
    ImGuiIO& io = ImGui::GetIO();
5104
54.1k
    ImDrawData* draw_data = &viewport->DrawDataP;
5105
5106
54.1k
    viewport->DrawData = draw_data; // Make publicly accessible
5107
54.1k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5108
54.1k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5109
54.1k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5110
54.1k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5111
5112
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5113
    // and to allow applications/backends to easily skip rendering.
5114
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5115
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5116
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5117
54.1k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5118
5119
54.1k
    draw_data->Valid = true;
5120
54.1k
    draw_data->CmdListsCount = 0;
5121
54.1k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5122
54.1k
    draw_data->DisplayPos = viewport->Pos;
5123
54.1k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5124
54.1k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5125
54.1k
    draw_data->OwnerViewport = viewport;
5126
54.1k
}
5127
5128
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5129
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5130
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5131
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5132
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5133
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5134
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5135
318k
{
5136
318k
    ImGuiWindow* window = GetCurrentWindow();
5137
318k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5138
318k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5139
318k
}
5140
5141
void ImGui::PopClipRect()
5142
159k
{
5143
159k
    ImGuiWindow* window = GetCurrentWindow();
5144
159k
    window->DrawList->PopClipRect();
5145
159k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5146
159k
}
5147
5148
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5149
0
{
5150
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5151
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5152
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5153
0
    return window;
5154
0
}
5155
5156
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5157
0
{
5158
0
    if ((col & IM_COL32_A_MASK) == 0)
5159
0
        return;
5160
5161
0
    ImGuiViewportP* viewport = window->Viewport;
5162
0
    ImRect viewport_rect = viewport->GetMainRect();
5163
5164
    // Draw behind window by moving the draw command at the FRONT of the draw list
5165
0
    {
5166
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5167
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5168
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5169
0
        draw_list->ChannelsMerge();
5170
0
        if (draw_list->CmdBuffer.Size == 0)
5171
0
            draw_list->AddDrawCmd();
5172
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5173
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5174
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5175
0
        IM_ASSERT(cmd.ElemCount == 6);
5176
0
        draw_list->CmdBuffer.pop_back();
5177
0
        draw_list->CmdBuffer.push_front(cmd);
5178
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5179
0
        draw_list->PopClipRect();
5180
0
    }
5181
5182
    // Draw over sibling docking nodes in a same docking tree
5183
0
    if (window->RootWindow->DockIsActive)
5184
0
    {
5185
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5186
0
        draw_list->ChannelsMerge();
5187
0
        if (draw_list->CmdBuffer.Size == 0)
5188
0
            draw_list->AddDrawCmd();
5189
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5190
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5191
0
        draw_list->PopClipRect();
5192
0
    }
5193
0
}
5194
5195
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5196
0
{
5197
0
    ImGuiContext& g = *GImGui;
5198
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5199
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5200
0
    {
5201
0
        ImGuiWindow* window = g.Windows[i];
5202
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5203
0
            continue;
5204
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5205
0
            break;
5206
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5207
0
            bottom_most_visible_window = window;
5208
0
    }
5209
0
    return bottom_most_visible_window;
5210
0
}
5211
5212
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5213
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5214
static void ImGui::RenderDimmedBackgrounds()
5215
54.1k
{
5216
54.1k
    ImGuiContext& g = *GImGui;
5217
54.1k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5218
54.1k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5219
54.1k
        return;
5220
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5221
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5222
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5223
0
        return;
5224
5225
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5226
0
    if (dim_bg_for_modal)
5227
0
    {
5228
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5229
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5230
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5231
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5232
0
    }
5233
0
    else if (dim_bg_for_window_list)
5234
0
    {
5235
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5236
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5237
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5238
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5239
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5240
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5241
5242
        // Draw border around CTRL+Tab target window
5243
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5244
0
        ImGuiViewport* viewport = window->Viewport;
5245
0
        float distance = g.FontSize;
5246
0
        ImRect bb = window->Rect();
5247
0
        bb.Expand(distance);
5248
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5249
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5250
0
        window->DrawList->ChannelsMerge();
5251
0
        if (window->DrawList->CmdBuffer.Size == 0)
5252
0
            window->DrawList->AddDrawCmd();
5253
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5254
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5255
0
        window->DrawList->PopClipRect();
5256
0
    }
5257
5258
    // Draw dimming background on _other_ viewports than the ones our windows are in
5259
0
    for (ImGuiViewportP* viewport : g.Viewports)
5260
0
    {
5261
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5262
0
            continue;
5263
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5264
0
            continue;
5265
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5266
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5267
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5268
0
    }
5269
0
}
5270
5271
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5272
void ImGui::EndFrame()
5273
108k
{
5274
108k
    ImGuiContext& g = *GImGui;
5275
108k
    IM_ASSERT(g.Initialized);
5276
5277
    // Don't process EndFrame() multiple times.
5278
108k
    if (g.FrameCountEnded == g.FrameCount)
5279
54.1k
        return;
5280
54.1k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5281
5282
54.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5283
5284
54.1k
    ErrorCheckEndFrameSanityChecks();
5285
5286
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5287
54.1k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5288
54.1k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5289
0
    {
5290
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5291
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5292
0
        if (viewport == NULL)
5293
0
            viewport = GetMainViewport();
5294
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5295
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5296
        {
5297
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5298
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5299
            viewport->PlatformHandleRaw = NULL;
5300
        }
5301
        else
5302
#endif
5303
0
        {
5304
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5305
0
        }
5306
0
    }
5307
5308
    // Hide implicit/fallback "Debug" window if it hasn't been used
5309
54.1k
    g.WithinFrameScopeWithImplicitWindow = false;
5310
54.1k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5311
54.1k
        g.CurrentWindow->Active = false;
5312
54.1k
    End();
5313
5314
    // Update navigation: CTRL+Tab, wrap-around requests
5315
54.1k
    NavEndFrame();
5316
5317
    // Update docking
5318
54.1k
    DockContextEndFrame(&g);
5319
5320
54.1k
    SetCurrentViewport(NULL, NULL);
5321
5322
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5323
54.1k
    if (g.DragDropActive)
5324
7
    {
5325
7
        bool is_delivered = g.DragDropPayload.Delivery;
5326
7
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5327
7
        if (is_delivered || is_elapsed)
5328
2
            ClearDragDrop();
5329
7
    }
5330
5331
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5332
54.1k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5333
0
    {
5334
0
        g.DragDropWithinSource = true;
5335
0
        SetTooltip("...");
5336
0
        g.DragDropWithinSource = false;
5337
0
    }
5338
5339
    // End frame
5340
54.1k
    g.WithinFrameScope = false;
5341
54.1k
    g.FrameCountEnded = g.FrameCount;
5342
5343
    // Initiate moving window + handle left-click and right-click focus
5344
54.1k
    UpdateMouseMovingWindowEndFrame();
5345
5346
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5347
54.1k
    UpdateViewportsEndFrame();
5348
5349
    // Sort the window list so that all child windows are after their parent
5350
    // We cannot do that on FocusWindow() because children may not exist yet
5351
54.1k
    g.WindowsTempSortBuffer.resize(0);
5352
54.1k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5353
54.1k
    for (ImGuiWindow* window : g.Windows)
5354
162k
    {
5355
162k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5356
51.0k
            continue;
5357
111k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5358
111k
    }
5359
5360
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5361
54.1k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5362
54.1k
    g.Windows.swap(g.WindowsTempSortBuffer);
5363
54.1k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5364
5365
    // Unlock font atlas
5366
54.1k
    g.IO.Fonts->Locked = false;
5367
5368
    // Clear Input data for next frame
5369
54.1k
    g.IO.MousePosPrev = g.IO.MousePos;
5370
54.1k
    g.IO.AppFocusLost = false;
5371
54.1k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5372
54.1k
    g.IO.InputQueueCharacters.resize(0);
5373
5374
54.1k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5375
54.1k
}
5376
5377
// Prepare the data for rendering so you can call GetDrawData()
5378
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5379
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5380
void ImGui::Render()
5381
54.1k
{
5382
54.1k
    ImGuiContext& g = *GImGui;
5383
54.1k
    IM_ASSERT(g.Initialized);
5384
5385
54.1k
    if (g.FrameCountEnded != g.FrameCount)
5386
54.1k
        EndFrame();
5387
54.1k
    if (g.FrameCountRendered == g.FrameCount)
5388
0
        return;
5389
54.1k
    g.FrameCountRendered = g.FrameCount;
5390
5391
54.1k
    g.IO.MetricsRenderWindows = 0;
5392
54.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5393
5394
    // Add background ImDrawList (for each active viewport)
5395
54.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5396
54.1k
    {
5397
54.1k
        InitViewportDrawData(viewport);
5398
54.1k
        if (viewport->BgFgDrawLists[0] != NULL)
5399
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5400
54.1k
    }
5401
5402
    // Draw modal/window whitening backgrounds
5403
54.1k
    RenderDimmedBackgrounds();
5404
5405
    // Add ImDrawList to render
5406
54.1k
    ImGuiWindow* windows_to_render_top_most[2];
5407
54.1k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5408
54.1k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5409
54.1k
    for (ImGuiWindow* window : g.Windows)
5410
162k
    {
5411
162k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5412
162k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5413
54.1k
            AddRootWindowToDrawData(window);
5414
162k
    }
5415
162k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5416
108k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5417
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5418
5419
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5420
54.1k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5421
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5422
5423
    // Setup ImDrawData structures for end-user
5424
54.1k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5425
54.1k
    for (ImGuiViewportP* viewport : g.Viewports)
5426
54.1k
    {
5427
54.1k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5428
5429
        // Add foreground ImDrawList (for each active viewport)
5430
54.1k
        if (viewport->BgFgDrawLists[1] != NULL)
5431
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5432
5433
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5434
54.1k
        ImDrawData* draw_data = &viewport->DrawDataP;
5435
54.1k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5436
54.1k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5437
101k
            draw_list->_PopUnusedDrawCmd();
5438
5439
54.1k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5440
54.1k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5441
54.1k
    }
5442
5443
54.1k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5444
54.1k
}
5445
5446
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5447
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5448
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5449
108k
{
5450
108k
    ImGuiContext& g = *GImGui;
5451
5452
108k
    const char* text_display_end;
5453
108k
    if (hide_text_after_double_hash)
5454
108k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5455
0
    else
5456
0
        text_display_end = text_end;
5457
5458
108k
    ImFont* font = g.Font;
5459
108k
    const float font_size = g.FontSize;
5460
108k
    if (text == text_display_end)
5461
0
        return ImVec2(0.0f, font_size);
5462
108k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5463
5464
    // Round
5465
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5466
    // FIXME: Investigate using ceilf or e.g.
5467
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5468
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5469
108k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5470
5471
108k
    return text_size;
5472
108k
}
5473
5474
// Find window given position, search front-to-back
5475
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5476
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5477
// called, aka before the next Begin(). Moving window isn't affected.
5478
static void FindHoveredWindow()
5479
54.1k
{
5480
54.1k
    ImGuiContext& g = *GImGui;
5481
5482
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5483
54.1k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5484
54.1k
    if (g.MovingWindow)
5485
40
        g.MovingWindow->Viewport = g.MouseViewport;
5486
5487
54.1k
    ImGuiWindow* hovered_window = NULL;
5488
54.1k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5489
54.1k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5490
40
        hovered_window = g.MovingWindow;
5491
5492
54.1k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5493
54.1k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5494
213k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5495
160k
    {
5496
160k
        ImGuiWindow* window = g.Windows[i];
5497
160k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5498
160k
        if (!window->Active || window->Hidden)
5499
55.5k
            continue;
5500
105k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5501
0
            continue;
5502
105k
        IM_ASSERT(window->Viewport);
5503
105k
        if (window->Viewport != g.MouseViewport)
5504
0
            continue;
5505
5506
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5507
105k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5508
105k
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5509
103k
            continue;
5510
5511
        // Support for one rectangular hole in any given window
5512
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5513
1.69k
        if (window->HitTestHoleSize.x != 0)
5514
0
        {
5515
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5516
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5517
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5518
0
                continue;
5519
0
        }
5520
5521
1.69k
        if (hovered_window == NULL)
5522
1.67k
            hovered_window = window;
5523
1.69k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5524
1.69k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5525
1.67k
            hovered_window_ignoring_moving_window = window;
5526
1.69k
        if (hovered_window && hovered_window_ignoring_moving_window)
5527
1.67k
            break;
5528
1.69k
    }
5529
5530
54.1k
    g.HoveredWindow = hovered_window;
5531
54.1k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5532
5533
54.1k
    if (g.MovingWindow)
5534
40
        g.MovingWindow->Viewport = moving_window_viewport;
5535
54.1k
}
5536
5537
bool ImGui::IsItemActive()
5538
108k
{
5539
108k
    ImGuiContext& g = *GImGui;
5540
108k
    if (g.ActiveId)
5541
88
        return g.ActiveId == g.LastItemData.ID;
5542
108k
    return false;
5543
108k
}
5544
5545
bool ImGui::IsItemActivated()
5546
0
{
5547
0
    ImGuiContext& g = *GImGui;
5548
0
    if (g.ActiveId)
5549
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5550
0
            return true;
5551
0
    return false;
5552
0
}
5553
5554
bool ImGui::IsItemDeactivated()
5555
0
{
5556
0
    ImGuiContext& g = *GImGui;
5557
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5558
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5559
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5560
0
}
5561
5562
bool ImGui::IsItemDeactivatedAfterEdit()
5563
0
{
5564
0
    ImGuiContext& g = *GImGui;
5565
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5566
0
}
5567
5568
// == GetItemID() == GetFocusID()
5569
bool ImGui::IsItemFocused()
5570
0
{
5571
0
    ImGuiContext& g = *GImGui;
5572
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5573
0
        return false;
5574
5575
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5576
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5577
0
    ImGuiWindow* window = g.CurrentWindow;
5578
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5579
0
        return false;
5580
5581
0
    return true;
5582
0
}
5583
5584
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5585
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5586
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5587
0
{
5588
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5589
0
}
5590
5591
bool ImGui::IsItemToggledOpen()
5592
0
{
5593
0
    ImGuiContext& g = *GImGui;
5594
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5595
0
}
5596
5597
bool ImGui::IsItemToggledSelection()
5598
0
{
5599
0
    ImGuiContext& g = *GImGui;
5600
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5601
0
}
5602
5603
bool ImGui::IsAnyItemHovered()
5604
0
{
5605
0
    ImGuiContext& g = *GImGui;
5606
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5607
0
}
5608
5609
bool ImGui::IsAnyItemActive()
5610
0
{
5611
0
    ImGuiContext& g = *GImGui;
5612
0
    return g.ActiveId != 0;
5613
0
}
5614
5615
bool ImGui::IsAnyItemFocused()
5616
0
{
5617
0
    ImGuiContext& g = *GImGui;
5618
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5619
0
}
5620
5621
bool ImGui::IsItemVisible()
5622
0
{
5623
0
    ImGuiContext& g = *GImGui;
5624
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5625
0
}
5626
5627
bool ImGui::IsItemEdited()
5628
0
{
5629
0
    ImGuiContext& g = *GImGui;
5630
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5631
0
}
5632
5633
// Allow next item to be overlapped by subsequent items.
5634
// This works by requiring HoveredId to match for two subsequent frames,
5635
// so if a following items overwrite it our interactions will naturally be disabled.
5636
void ImGui::SetNextItemAllowOverlap()
5637
0
{
5638
0
    ImGuiContext& g = *GImGui;
5639
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5640
0
}
5641
5642
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5643
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5644
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5645
void ImGui::SetItemAllowOverlap()
5646
{
5647
    ImGuiContext& g = *GImGui;
5648
    ImGuiID id = g.LastItemData.ID;
5649
    if (g.HoveredId == id)
5650
        g.HoveredIdAllowOverlap = true;
5651
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5652
        g.ActiveIdAllowOverlap = true;
5653
}
5654
#endif
5655
5656
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5657
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5658
40
{
5659
40
    ImGuiContext& g = *GImGui;
5660
40
    IM_ASSERT(g.ActiveId != 0);
5661
40
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5662
40
    g.ActiveIdUsingAllKeyboardKeys = true;
5663
40
    NavMoveRequestCancel();
5664
40
}
5665
5666
ImGuiID ImGui::GetItemID()
5667
0
{
5668
0
    ImGuiContext& g = *GImGui;
5669
0
    return g.LastItemData.ID;
5670
0
}
5671
5672
ImVec2 ImGui::GetItemRectMin()
5673
0
{
5674
0
    ImGuiContext& g = *GImGui;
5675
0
    return g.LastItemData.Rect.Min;
5676
0
}
5677
5678
ImVec2 ImGui::GetItemRectMax()
5679
0
{
5680
0
    ImGuiContext& g = *GImGui;
5681
0
    return g.LastItemData.Rect.Max;
5682
0
}
5683
5684
ImVec2 ImGui::GetItemRectSize()
5685
0
{
5686
0
    ImGuiContext& g = *GImGui;
5687
0
    return g.LastItemData.Rect.GetSize();
5688
0
}
5689
5690
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5691
51.0k
{
5692
51.0k
    ImGuiContext& g = *GImGui;
5693
51.0k
    ImGuiWindow* parent_window = g.CurrentWindow;
5694
5695
51.0k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5696
51.0k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5697
5698
    // Size
5699
51.0k
    const ImVec2 content_avail = GetContentRegionAvail();
5700
51.0k
    ImVec2 size = ImTrunc(size_arg);
5701
51.0k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5702
51.0k
    if (size.x <= 0.0f)
5703
48.0k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5704
51.0k
    if (size.y <= 0.0f)
5705
45.2k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5706
51.0k
    SetNextWindowSize(size);
5707
5708
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5709
51.0k
    const char* temp_window_name;
5710
51.0k
    if (name)
5711
51.0k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5712
0
    else
5713
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5714
5715
51.0k
    const float backup_border_size = g.Style.ChildBorderSize;
5716
51.0k
    if (!border)
5717
33.5k
        g.Style.ChildBorderSize = 0.0f;
5718
51.0k
    bool ret = Begin(temp_window_name, NULL, flags);
5719
51.0k
    g.Style.ChildBorderSize = backup_border_size;
5720
5721
51.0k
    ImGuiWindow* child_window = g.CurrentWindow;
5722
51.0k
    child_window->ChildId = id;
5723
51.0k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5724
5725
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5726
    // While this is not really documented/defined, it seems that the expected thing to do.
5727
51.0k
    if (child_window->BeginCount == 1)
5728
51.0k
        parent_window->DC.CursorPos = child_window->Pos;
5729
5730
    // Process navigation-in immediately so NavInit can run on first frame
5731
    // Can enter a child if (A) it has navigatable items or (B) it can be scrolled.
5732
51.0k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5733
51.0k
    if (g.ActiveId == temp_id_for_activation)
5734
9
        ClearActiveID();
5735
51.0k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5736
11
    {
5737
11
        FocusWindow(child_window);
5738
11
        NavInitWindow(child_window, false);
5739
11
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5740
11
        g.ActiveIdSource = g.NavInputSource;
5741
11
    }
5742
51.0k
    return ret;
5743
51.0k
}
5744
5745
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5746
51.0k
{
5747
51.0k
    ImGuiWindow* window = GetCurrentWindow();
5748
51.0k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5749
51.0k
}
5750
5751
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5752
0
{
5753
0
    IM_ASSERT(id != 0);
5754
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5755
0
}
5756
5757
void ImGui::EndChild()
5758
51.0k
{
5759
51.0k
    ImGuiContext& g = *GImGui;
5760
51.0k
    ImGuiWindow* window = g.CurrentWindow;
5761
5762
51.0k
    IM_ASSERT(g.WithinEndChild == false);
5763
51.0k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5764
5765
51.0k
    g.WithinEndChild = true;
5766
51.0k
    if (window->BeginCount > 1)
5767
0
    {
5768
0
        End();
5769
0
    }
5770
51.0k
    else
5771
51.0k
    {
5772
51.0k
        ImVec2 sz = window->Size;
5773
51.0k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5774
48.0k
            sz.x = ImMax(4.0f, sz.x);
5775
51.0k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5776
45.2k
            sz.y = ImMax(4.0f, sz.y);
5777
51.0k
        End();
5778
5779
51.0k
        ImGuiWindow* parent_window = g.CurrentWindow;
5780
51.0k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5781
51.0k
        ItemSize(sz);
5782
51.0k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavWindowHasScrollY) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5783
48.0k
        {
5784
48.0k
            ItemAdd(bb, window->ChildId);
5785
48.0k
            RenderNavHighlight(bb, window->ChildId);
5786
5787
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5788
48.0k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5789
39.4k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5790
48.0k
        }
5791
2.91k
        else
5792
2.91k
        {
5793
            // Not navigable into
5794
2.91k
            ItemAdd(bb, 0);
5795
5796
            // But when flattened we directly reach items, adjust active layer mask accordingly
5797
2.91k
            if (window->Flags & ImGuiWindowFlags_NavFlattened)
5798
0
                parent_window->DC.NavLayersActiveMaskNext |= window->DC.NavLayersActiveMaskNext;
5799
2.91k
        }
5800
51.0k
        if (g.HoveredWindow == window)
5801
1
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5802
51.0k
    }
5803
51.0k
    g.WithinEndChild = false;
5804
51.0k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5805
51.0k
}
5806
5807
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5808
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5809
0
{
5810
0
    ImGuiContext& g = *GImGui;
5811
0
    const ImGuiStyle& style = g.Style;
5812
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5813
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5814
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5815
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5816
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5817
0
    PopStyleVar(3);
5818
0
    PopStyleColor();
5819
0
    return ret;
5820
0
}
5821
5822
void ImGui::EndChildFrame()
5823
0
{
5824
0
    EndChild();
5825
0
}
5826
5827
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5828
8
{
5829
8
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5830
8
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5831
8
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5832
8
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5833
8
}
5834
5835
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5836
159k
{
5837
159k
    ImGuiContext& g = *GImGui;
5838
159k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5839
159k
}
5840
5841
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5842
159k
{
5843
159k
    ImGuiID id = ImHashStr(name);
5844
159k
    return FindWindowByID(id);
5845
159k
}
5846
5847
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5848
0
{
5849
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5850
0
    window->ViewportPos = main_viewport->Pos;
5851
0
    if (settings->ViewportId)
5852
0
    {
5853
0
        window->ViewportId = settings->ViewportId;
5854
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5855
0
    }
5856
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5857
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5858
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5859
0
    window->Collapsed = settings->Collapsed;
5860
0
    window->DockId = settings->DockId;
5861
0
    window->DockOrder = settings->DockOrder;
5862
0
}
5863
5864
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5865
159k
{
5866
159k
    ImGuiContext& g = *GImGui;
5867
5868
159k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5869
159k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5870
159k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5871
2
    {
5872
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5873
2
        g.WindowsFocusOrder.push_back(window);
5874
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5875
2
    }
5876
159k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5877
0
    {
5878
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5879
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5880
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5881
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5882
0
        window->FocusOrder = -1;
5883
0
    }
5884
159k
    window->IsExplicitChild = new_is_explicit_child;
5885
159k
}
5886
5887
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5888
3
{
5889
    // Initial window state with e.g. default/arbitrary window position
5890
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5891
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5892
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5893
3
    window->Size = window->SizeFull = ImVec2(0, 0);
5894
3
    window->ViewportPos = main_viewport->Pos;
5895
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5896
5897
3
    if (settings != NULL)
5898
0
    {
5899
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5900
0
        ApplyWindowSettings(window, settings);
5901
0
    }
5902
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5903
5904
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5905
0
    {
5906
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5907
0
        window->AutoFitOnlyGrows = false;
5908
0
    }
5909
3
    else
5910
3
    {
5911
3
        if (window->Size.x <= 0.0f)
5912
3
            window->AutoFitFramesX = 2;
5913
3
        if (window->Size.y <= 0.0f)
5914
3
            window->AutoFitFramesY = 2;
5915
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5916
3
    }
5917
3
}
5918
5919
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5920
3
{
5921
    // Create window the first time
5922
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5923
3
    ImGuiContext& g = *GImGui;
5924
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5925
3
    window->Flags = flags;
5926
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5927
5928
3
    ImGuiWindowSettings* settings = NULL;
5929
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5930
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5931
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5932
5933
3
    InitOrLoadWindowSettings(window, settings);
5934
5935
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5936
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5937
3
    else
5938
3
        g.Windows.push_back(window);
5939
5940
3
    return window;
5941
3
}
5942
5943
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5944
0
{
5945
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5946
0
}
5947
5948
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5949
216k
{
5950
216k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5951
216k
}
5952
5953
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5954
318k
{
5955
318k
    ImGuiContext& g = *GImGui;
5956
318k
    ImVec2 new_size = size_desired;
5957
318k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5958
0
    {
5959
        // Using -1,-1 on either X/Y axis to preserve the current size.
5960
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5961
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5962
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5963
0
        if (g.NextWindowData.SizeCallback)
5964
0
        {
5965
0
            ImGuiSizeCallbackData data;
5966
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5967
0
            data.Pos = window->Pos;
5968
0
            data.CurrentSize = window->SizeFull;
5969
0
            data.DesiredSize = new_size;
5970
0
            g.NextWindowData.SizeCallback(&data);
5971
0
            new_size = data.DesiredSize;
5972
0
        }
5973
0
        new_size.x = IM_TRUNC(new_size.x);
5974
0
        new_size.y = IM_TRUNC(new_size.y);
5975
0
    }
5976
5977
    // Minimum size
5978
318k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5979
216k
    {
5980
216k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5981
216k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5982
216k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5983
216k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5984
216k
    }
5985
318k
    return new_size;
5986
318k
}
5987
5988
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5989
159k
{
5990
159k
    bool preserve_old_content_sizes = false;
5991
159k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5992
3.12k
        preserve_old_content_sizes = true;
5993
156k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5994
0
        preserve_old_content_sizes = true;
5995
159k
    if (preserve_old_content_sizes)
5996
3.12k
    {
5997
3.12k
        *content_size_current = window->ContentSize;
5998
3.12k
        *content_size_ideal = window->ContentSizeIdeal;
5999
3.12k
        return;
6000
3.12k
    }
6001
6002
156k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6003
156k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6004
156k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6005
156k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6006
156k
}
6007
6008
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6009
159k
{
6010
159k
    ImGuiContext& g = *GImGui;
6011
159k
    ImGuiStyle& style = g.Style;
6012
159k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6013
159k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6014
159k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6015
159k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6016
159k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6017
0
    {
6018
        // Tooltip always resize
6019
0
        return size_desired;
6020
0
    }
6021
159k
    else
6022
159k
    {
6023
        // Maximum window size is determined by the viewport size or monitor size
6024
159k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
6025
159k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
6026
159k
        ImVec2 size_min = style.WindowMinSize;
6027
159k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6028
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
6029
6030
159k
        ImVec2 avail_size = window->Viewport->WorkSize;
6031
159k
        if (window->ViewportOwned)
6032
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
6033
159k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6034
159k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6035
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
6036
159k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
6037
6038
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6039
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6040
159k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6041
159k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6042
159k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6043
159k
        if (will_have_scrollbar_x)
6044
51.0k
            size_auto_fit.y += style.ScrollbarSize;
6045
159k
        if (will_have_scrollbar_y)
6046
342
            size_auto_fit.x += style.ScrollbarSize;
6047
159k
        return size_auto_fit;
6048
159k
    }
6049
159k
}
6050
6051
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6052
0
{
6053
0
    ImVec2 size_contents_current;
6054
0
    ImVec2 size_contents_ideal;
6055
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6056
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6057
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6058
0
    return size_final;
6059
0
}
6060
6061
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6062
156k
{
6063
156k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6064
0
        return ImGuiCol_PopupBg;
6065
156k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6066
51.0k
        return ImGuiCol_ChildBg;
6067
105k
    return ImGuiCol_WindowBg;
6068
156k
}
6069
6070
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6071
0
{
6072
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6073
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6074
0
    ImVec2 size_expected = pos_max - pos_min;
6075
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6076
0
    *out_pos = pos_min;
6077
0
    if (corner_norm.x == 0.0f)
6078
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6079
0
    if (corner_norm.y == 0.0f)
6080
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6081
0
    *out_size = size_constrained;
6082
0
}
6083
6084
// Data for resizing from corner
6085
struct ImGuiResizeGripDef
6086
{
6087
    ImVec2  CornerPosN;
6088
    ImVec2  InnerDir;
6089
    int     AngleMin12, AngleMax12;
6090
};
6091
static const ImGuiResizeGripDef resize_grip_def[4] =
6092
{
6093
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6094
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6095
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6096
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6097
};
6098
6099
// Data for resizing from borders
6100
struct ImGuiResizeBorderDef
6101
{
6102
    ImVec2 InnerDir;
6103
    ImVec2 SegmentN1, SegmentN2;
6104
    float  OuterAngle;
6105
};
6106
static const ImGuiResizeBorderDef resize_border_def[4] =
6107
{
6108
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6109
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6110
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6111
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6112
};
6113
6114
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6115
0
{
6116
0
    ImRect rect = window->Rect();
6117
0
    if (thickness == 0.0f)
6118
0
        rect.Max -= ImVec2(1, 1);
6119
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6120
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6121
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6122
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6123
0
    IM_ASSERT(0);
6124
0
    return ImRect();
6125
0
}
6126
6127
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6128
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6129
0
{
6130
0
    IM_ASSERT(n >= 0 && n < 4);
6131
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6132
0
    id = ImHashStr("#RESIZE", 0, id);
6133
0
    id = ImHashData(&n, sizeof(int), id);
6134
0
    return id;
6135
0
}
6136
6137
// Borders (Left, Right, Up, Down)
6138
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6139
0
{
6140
0
    IM_ASSERT(dir >= 0 && dir < 4);
6141
0
    int n = (int)dir + 4;
6142
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6143
0
    id = ImHashStr("#RESIZE", 0, id);
6144
0
    id = ImHashData(&n, sizeof(int), id);
6145
0
    return id;
6146
0
}
6147
6148
// Handle resize for: Resize Grips, Borders, Gamepad
6149
// Return true when using auto-fit (double-click on resize grip)
6150
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6151
156k
{
6152
156k
    ImGuiContext& g = *GImGui;
6153
156k
    ImGuiWindowFlags flags = window->Flags;
6154
6155
156k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6156
51.0k
        return false;
6157
105k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6158
54.1k
        return false;
6159
6160
51.0k
    bool ret_auto_fit = false;
6161
51.0k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
6162
51.0k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6163
51.0k
    const float grip_hover_inner_size = IM_TRUNC(grip_draw_size * 0.75f);
6164
51.0k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6165
6166
51.0k
    ImRect clamp_rect = visibility_rect;
6167
51.0k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6168
51.0k
    if (window_move_from_title_bar)
6169
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6170
6171
51.0k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6172
51.0k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6173
6174
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6175
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6176
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6177
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6178
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6179
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6180
51.0k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6181
51.0k
    if (clip_with_viewport_rect)
6182
51.0k
        window->ClipRect = window->Viewport->GetMainRect();
6183
6184
    // Resize grips and borders are on layer 1
6185
51.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6186
6187
    // Manual resize grips
6188
51.0k
    PushID("#RESIZE");
6189
102k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6190
51.0k
    {
6191
51.0k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6192
51.0k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6193
6194
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6195
51.0k
        bool hovered, held;
6196
51.0k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6197
51.0k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6198
51.0k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6199
51.0k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6200
51.0k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6201
51.0k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6202
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6203
51.0k
        if (hovered || held)
6204
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6205
6206
51.0k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6207
0
        {
6208
            // Manual auto-fit when double-clicking
6209
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6210
0
            ret_auto_fit = true;
6211
0
            ClearActiveID();
6212
0
        }
6213
51.0k
        else if (held)
6214
0
        {
6215
            // Resize from any of the four corners
6216
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6217
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6218
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6219
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6220
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6221
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6222
0
        }
6223
6224
        // Only lower-left grip is visible before hovering/activating
6225
51.0k
        if (resize_grip_n == 0 || held || hovered)
6226
51.0k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6227
51.0k
    }
6228
51.0k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6229
0
    {
6230
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6231
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6232
6233
0
        bool hovered, held;
6234
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6235
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6236
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6237
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6238
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6239
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6240
0
        {
6241
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6242
0
            if (held)
6243
0
                *border_held = border_n;
6244
0
        }
6245
0
        if (held)
6246
0
        {
6247
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6248
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6249
0
            ImVec2 border_target = window->Pos;
6250
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6251
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6252
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6253
0
        }
6254
0
    }
6255
51.0k
    PopID();
6256
6257
    // Restore nav layer
6258
51.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6259
6260
    // Navigation resize (keyboard/gamepad)
6261
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6262
    // Not even sure the callback works here.
6263
51.0k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6264
0
    {
6265
0
        ImVec2 nav_resize_dir;
6266
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6267
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6268
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6269
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6270
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6271
0
        {
6272
0
            const float NAV_RESIZE_SPEED = 600.0f;
6273
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6274
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6275
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6276
0
            g.NavWindowingToggleLayer = false;
6277
0
            g.NavDisableMouseHover = true;
6278
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6279
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6280
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6281
0
            {
6282
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6283
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6284
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6285
0
            }
6286
0
        }
6287
0
    }
6288
6289
    // Apply back modified position/size to window
6290
51.0k
    if (size_target.x != FLT_MAX)
6291
0
    {
6292
0
        window->SizeFull = size_target;
6293
0
        MarkIniSettingsDirty(window);
6294
0
    }
6295
51.0k
    if (pos_target.x != FLT_MAX)
6296
0
    {
6297
0
        window->Pos = ImTrunc(pos_target);
6298
0
        MarkIniSettingsDirty(window);
6299
0
    }
6300
6301
51.0k
    window->Size = window->SizeFull;
6302
51.0k
    return ret_auto_fit;
6303
105k
}
6304
6305
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6306
108k
{
6307
108k
    ImGuiContext& g = *GImGui;
6308
108k
    ImVec2 size_for_clamping = window->Size;
6309
108k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6310
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6311
108k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6312
108k
}
6313
6314
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6315
156k
{
6316
156k
    ImGuiContext& g = *GImGui;
6317
156k
    float rounding = window->WindowRounding;
6318
156k
    float border_size = window->WindowBorderSize;
6319
156k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6320
122k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6321
6322
156k
    int border_held = window->ResizeBorderHeld;
6323
156k
    if (border_held != -1)
6324
0
    {
6325
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6326
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6327
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6328
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6329
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6330
0
    }
6331
156k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6332
0
    {
6333
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6334
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6335
0
    }
6336
156k
}
6337
6338
// Draw background and borders
6339
// Draw and handle scrollbars
6340
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6341
159k
{
6342
159k
    ImGuiContext& g = *GImGui;
6343
159k
    ImGuiStyle& style = g.Style;
6344
159k
    ImGuiWindowFlags flags = window->Flags;
6345
6346
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6347
159k
    IM_ASSERT(window->BeginCount == 0);
6348
159k
    window->SkipItems = false;
6349
6350
    // Draw window + handle manual resize
6351
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6352
159k
    const float window_rounding = window->WindowRounding;
6353
159k
    const float window_border_size = window->WindowBorderSize;
6354
159k
    if (window->Collapsed)
6355
3.12k
    {
6356
        // Title bar only
6357
3.12k
        const float backup_border_size = style.FrameBorderSize;
6358
3.12k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6359
3.12k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6360
3.12k
        if (window->ViewportOwned)
6361
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6362
3.12k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6363
3.12k
        g.Style.FrameBorderSize = backup_border_size;
6364
3.12k
    }
6365
156k
    else
6366
156k
    {
6367
        // Window background
6368
156k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6369
156k
        {
6370
156k
            bool is_docking_transparent_payload = false;
6371
156k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6372
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6373
0
                    is_docking_transparent_payload = true;
6374
6375
156k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6376
156k
            if (window->ViewportOwned)
6377
0
            {
6378
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6379
0
                if (is_docking_transparent_payload)
6380
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6381
0
            }
6382
156k
            else
6383
156k
            {
6384
                // Adjust alpha. For docking
6385
156k
                bool override_alpha = false;
6386
156k
                float alpha = 1.0f;
6387
156k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6388
0
                {
6389
0
                    alpha = g.NextWindowData.BgAlphaVal;
6390
0
                    override_alpha = true;
6391
0
                }
6392
156k
                if (is_docking_transparent_payload)
6393
0
                {
6394
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6395
0
                    override_alpha = true;
6396
0
                }
6397
156k
                if (override_alpha)
6398
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6399
156k
            }
6400
6401
            // Render, for docked windows and host windows we ensure bg goes before decorations
6402
156k
            if (window->DockIsActive)
6403
0
                window->DockNode->LastBgColor = bg_col;
6404
156k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6405
156k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6406
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6407
156k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6408
156k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6409
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6410
156k
        }
6411
156k
        if (window->DockIsActive)
6412
0
            window->DockNode->IsBgDrawnThisFrame = true;
6413
6414
        // Title bar
6415
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6416
        // in order for their pos/size to be matching their undocking state.)
6417
156k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6418
105k
        {
6419
105k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6420
105k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6421
105k
        }
6422
6423
        // Menu bar
6424
156k
        if (flags & ImGuiWindowFlags_MenuBar)
6425
0
        {
6426
0
            ImRect menu_bar_rect = window->MenuBarRect();
6427
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6428
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6429
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6430
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6431
0
        }
6432
6433
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6434
156k
        ImGuiDockNode* node = window->DockNode;
6435
156k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6436
0
        {
6437
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6438
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6439
0
            ImVec2 p = node->Pos;
6440
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6441
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6442
0
            KeepAliveID(unhide_id);
6443
0
            bool hovered, held;
6444
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6445
0
                node->WantHiddenTabBarToggle = true;
6446
0
            else if (held && IsMouseDragging(0))
6447
0
                StartMouseMovingWindowOrNode(window, node, true);
6448
6449
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6450
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6451
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6452
0
        }
6453
6454
        // Scrollbars
6455
156k
        if (window->ScrollbarX)
6456
51.0k
            Scrollbar(ImGuiAxis_X);
6457
156k
        if (window->ScrollbarY)
6458
52.4k
            Scrollbar(ImGuiAxis_Y);
6459
6460
        // Render resize grips (after their input handling so we don't have a frame of latency)
6461
156k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6462
105k
        {
6463
210k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6464
105k
            {
6465
105k
                const ImU32 col = resize_grip_col[resize_grip_n];
6466
105k
                if ((col & IM_COL32_A_MASK) == 0)
6467
54.1k
                    continue;
6468
51.0k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6469
51.0k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6470
51.0k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6471
51.0k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6472
51.0k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6473
51.0k
                window->DrawList->PathFillConvex(col);
6474
51.0k
            }
6475
105k
        }
6476
6477
        // Borders (for dock node host they will be rendered over after the tab bar)
6478
156k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6479
156k
            RenderWindowOuterBorders(window);
6480
156k
    }
6481
159k
}
6482
6483
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6484
// Render title text, collapse button, close button
6485
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6486
108k
{
6487
108k
    ImGuiContext& g = *GImGui;
6488
108k
    ImGuiStyle& style = g.Style;
6489
108k
    ImGuiWindowFlags flags = window->Flags;
6490
6491
108k
    const bool has_close_button = (p_open != NULL);
6492
108k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6493
6494
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6495
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6496
108k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6497
108k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6498
108k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6499
6500
    // Layout buttons
6501
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6502
108k
    float pad_l = style.FramePadding.x;
6503
108k
    float pad_r = style.FramePadding.x;
6504
108k
    float button_sz = g.FontSize;
6505
108k
    ImVec2 close_button_pos;
6506
108k
    ImVec2 collapse_button_pos;
6507
108k
    if (has_close_button)
6508
0
    {
6509
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6510
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6511
0
    }
6512
108k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6513
0
    {
6514
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6515
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6516
0
    }
6517
108k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6518
108k
    {
6519
108k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6520
108k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6521
108k
    }
6522
6523
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6524
108k
    if (has_collapse_button)
6525
108k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6526
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6527
6528
    // Close button
6529
108k
    if (has_close_button)
6530
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6531
0
            *p_open = false;
6532
6533
108k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6534
108k
    g.CurrentItemFlags = item_flags_backup;
6535
6536
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6537
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6538
108k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6539
108k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6540
6541
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6542
    // while uncentered title text will still reach edges correctly.
6543
108k
    if (pad_l > style.FramePadding.x)
6544
108k
        pad_l += g.Style.ItemInnerSpacing.x;
6545
108k
    if (pad_r > style.FramePadding.x)
6546
0
        pad_r += g.Style.ItemInnerSpacing.x;
6547
108k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6548
0
    {
6549
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6550
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6551
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6552
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6553
0
    }
6554
6555
108k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6556
108k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6557
108k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6558
0
    {
6559
0
        ImVec2 marker_pos;
6560
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6561
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6562
0
        if (marker_pos.x > layout_r.Min.x)
6563
0
        {
6564
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6565
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6566
0
        }
6567
0
    }
6568
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6569
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6570
108k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6571
108k
}
6572
6573
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6574
159k
{
6575
159k
    window->ParentWindow = parent_window;
6576
159k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6577
159k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6578
51.0k
    {
6579
51.0k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6580
51.0k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6581
51.0k
            window->RootWindow = parent_window->RootWindow;
6582
51.0k
    }
6583
159k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6584
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6585
159k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6586
51.0k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6587
159k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6588
0
    {
6589
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6590
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6591
0
    }
6592
159k
}
6593
6594
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6595
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6596
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6597
// - WindowA            // FindBlockingModal() returns Modal1
6598
//   - WindowB          //                  .. returns Modal1
6599
//   - Modal1           //                  .. returns Modal2
6600
//      - WindowC       //                  .. returns Modal2
6601
//          - WindowD   //                  .. returns Modal2
6602
//          - Modal2    //                  .. returns Modal2
6603
//            - WindowE //                  .. returns NULL
6604
// Notes:
6605
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6606
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6607
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6608
1.24k
{
6609
1.24k
    ImGuiContext& g = *GImGui;
6610
1.24k
    if (g.OpenPopupStack.Size <= 0)
6611
1.24k
        return NULL;
6612
6613
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6614
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6615
0
    {
6616
0
        ImGuiWindow* popup_window = popup_data.Window;
6617
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6618
0
            continue;
6619
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6620
0
            continue;
6621
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6622
0
            return popup_window;
6623
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6624
0
            continue;
6625
0
        return popup_window;                                        // Place window right below first block modal
6626
0
    }
6627
0
    return NULL;
6628
0
}
6629
6630
// Push a new Dear ImGui window to add widgets to.
6631
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6632
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6633
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6634
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6635
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6636
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6637
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6638
159k
{
6639
159k
    ImGuiContext& g = *GImGui;
6640
159k
    const ImGuiStyle& style = g.Style;
6641
159k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6642
159k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6643
159k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6644
6645
    // Find or create
6646
159k
    ImGuiWindow* window = FindWindowByName(name);
6647
159k
    const bool window_just_created = (window == NULL);
6648
159k
    if (window_just_created)
6649
3
        window = CreateNewWindow(name, flags);
6650
6651
    // Automatically disable manual moving/resizing when NoInputs is set
6652
159k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6653
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6654
6655
159k
    if (flags & ImGuiWindowFlags_NavFlattened)
6656
159k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6657
6658
159k
    const int current_frame = g.FrameCount;
6659
159k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6660
159k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6661
6662
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6663
159k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6664
159k
    if (flags & ImGuiWindowFlags_Popup)
6665
0
    {
6666
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6667
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6668
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6669
0
    }
6670
6671
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6672
159k
    const bool window_was_appearing = window->Appearing;
6673
159k
    if (first_begin_of_the_frame)
6674
159k
    {
6675
159k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6676
159k
        window->Appearing = window_just_activated_by_user;
6677
159k
        if (window->Appearing)
6678
4
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6679
159k
        window->FlagsPreviousFrame = window->Flags;
6680
159k
        window->Flags = (ImGuiWindowFlags)flags;
6681
159k
        window->LastFrameActive = current_frame;
6682
159k
        window->LastTimeActive = (float)g.Time;
6683
159k
        window->BeginOrderWithinParent = 0;
6684
159k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6685
159k
    }
6686
0
    else
6687
0
    {
6688
0
        flags = window->Flags;
6689
0
    }
6690
6691
    // Docking
6692
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6693
159k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6694
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6695
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6696
159k
    if (first_begin_of_the_frame)
6697
159k
    {
6698
159k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6699
159k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6700
159k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6701
159k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6702
159k
        if (has_dock_node || new_auto_dock_node)
6703
0
        {
6704
0
            BeginDocked(window, p_open);
6705
0
            flags = window->Flags;
6706
0
            if (window->DockIsActive)
6707
0
            {
6708
0
                IM_ASSERT(window->DockNode != NULL);
6709
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6710
0
            }
6711
6712
            // Amend the Appearing flag
6713
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6714
0
            {
6715
0
                window->Appearing = true;
6716
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6717
0
            }
6718
0
        }
6719
159k
        else
6720
159k
        {
6721
159k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6722
159k
        }
6723
159k
    }
6724
6725
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6726
159k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6727
159k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6728
159k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6729
6730
    // We allow window memory to be compacted so recreate the base stack when needed.
6731
159k
    if (window->IDStack.Size == 0)
6732
0
        window->IDStack.push_back(window->ID);
6733
6734
    // Add to stack
6735
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6736
159k
    g.CurrentWindow = window;
6737
159k
    ImGuiWindowStackData window_stack_data;
6738
159k
    window_stack_data.Window = window;
6739
159k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6740
159k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6741
159k
    g.CurrentWindowStack.push_back(window_stack_data);
6742
159k
    if (flags & ImGuiWindowFlags_ChildMenu)
6743
0
        g.BeginMenuCount++;
6744
6745
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6746
159k
    if (first_begin_of_the_frame)
6747
159k
    {
6748
159k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6749
159k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6750
159k
    }
6751
6752
    // Add to focus scope stack
6753
159k
    PushFocusScope(window->ID);
6754
159k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6755
159k
    g.CurrentWindow = NULL;
6756
6757
    // Add to popup stack
6758
159k
    if (flags & ImGuiWindowFlags_Popup)
6759
0
    {
6760
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6761
0
        popup_ref.Window = window;
6762
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6763
0
        g.BeginPopupStack.push_back(popup_ref);
6764
0
        window->PopupId = popup_ref.PopupId;
6765
0
    }
6766
6767
    // Process SetNextWindow***() calls
6768
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6769
159k
    bool window_pos_set_by_api = false;
6770
159k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6771
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6772
0
    {
6773
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6774
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6775
0
        {
6776
            // May be processed on the next frame if this is our first frame and we are measuring size
6777
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6778
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6779
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6780
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6781
0
        }
6782
0
        else
6783
0
        {
6784
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6785
0
        }
6786
0
    }
6787
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6788
105k
    {
6789
105k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6790
105k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6791
105k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6792
105k
    }
6793
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6794
0
    {
6795
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6796
0
        {
6797
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6798
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6799
0
        }
6800
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6801
0
        {
6802
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6803
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6804
0
        }
6805
0
    }
6806
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6807
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6808
159k
    else if (first_begin_of_the_frame)
6809
159k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6810
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6811
0
        window->WindowClass = g.NextWindowData.WindowClass;
6812
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6813
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6814
159k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6815
0
        FocusWindow(window);
6816
159k
    if (window->Appearing)
6817
4
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6818
6819
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6820
159k
    if (first_begin_of_the_frame)
6821
159k
    {
6822
        // Initialize
6823
159k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6824
159k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6825
159k
        window->Active = true;
6826
159k
        window->HasCloseButton = (p_open != NULL);
6827
159k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6828
159k
        window->IDStack.resize(1);
6829
159k
        window->DrawList->_ResetForNewFrame();
6830
159k
        window->DC.CurrentTableIdx = -1;
6831
159k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6832
0
        {
6833
0
            window->DrawList->ChannelsSplit(2);
6834
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6835
0
        }
6836
6837
        // Restore buffer capacity when woken from a compacted state, to avoid
6838
159k
        if (window->MemoryCompacted)
6839
0
            GcAwakeTransientWindowBuffers(window);
6840
6841
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6842
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6843
159k
        bool window_title_visible_elsewhere = false;
6844
159k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6845
0
            window_title_visible_elsewhere = true;
6846
159k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6847
0
            window_title_visible_elsewhere = true;
6848
159k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6849
0
        {
6850
0
            size_t buf_len = (size_t)window->NameBufLen;
6851
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6852
0
            window->NameBufLen = (int)buf_len;
6853
0
        }
6854
6855
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6856
6857
        // Update contents size from last frame for auto-fitting (or use explicit size)
6858
159k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6859
6860
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6861
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6862
        // it has a single usage before this code block and may be set below before it is finally checked.
6863
159k
        if (window->HiddenFramesCanSkipItems > 0)
6864
0
            window->HiddenFramesCanSkipItems--;
6865
159k
        if (window->HiddenFramesCannotSkipItems > 0)
6866
2
            window->HiddenFramesCannotSkipItems--;
6867
159k
        if (window->HiddenFramesForRenderOnly > 0)
6868
0
            window->HiddenFramesForRenderOnly--;
6869
6870
        // Hide new windows for one frame until they calculate their size
6871
159k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6872
1
            window->HiddenFramesCannotSkipItems = 1;
6873
6874
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6875
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6876
159k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6877
0
        {
6878
0
            window->HiddenFramesCannotSkipItems = 1;
6879
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6880
0
            {
6881
0
                if (!window_size_x_set_by_api)
6882
0
                    window->Size.x = window->SizeFull.x = 0.f;
6883
0
                if (!window_size_y_set_by_api)
6884
0
                    window->Size.y = window->SizeFull.y = 0.f;
6885
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6886
0
            }
6887
0
        }
6888
6889
        // SELECT VIEWPORT
6890
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6891
6892
159k
        WindowSelectViewport(window);
6893
159k
        SetCurrentViewport(window, window->Viewport);
6894
159k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6895
159k
        SetCurrentWindow(window);
6896
159k
        flags = window->Flags;
6897
6898
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6899
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6900
6901
159k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
6902
51.0k
            window->WindowBorderSize = style.ChildBorderSize;
6903
108k
        else
6904
108k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6905
159k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6906
33.5k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6907
125k
        else
6908
125k
            window->WindowPadding = style.WindowPadding;
6909
6910
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6911
159k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6912
159k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6913
6914
159k
        bool use_current_size_for_scrollbar_x = window_just_created;
6915
159k
        bool use_current_size_for_scrollbar_y = window_just_created;
6916
6917
        // Collapse window by double-clicking on title bar
6918
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6919
159k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6920
108k
        {
6921
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6922
108k
            ImRect title_bar_rect = window->TitleBarRect();
6923
108k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6924
2
                window->WantCollapseToggle = true;
6925
108k
            if (window->WantCollapseToggle)
6926
2
            {
6927
2
                window->Collapsed = !window->Collapsed;
6928
2
                if (!window->Collapsed)
6929
1
                    use_current_size_for_scrollbar_y = true;
6930
2
                MarkIniSettingsDirty(window);
6931
2
            }
6932
108k
        }
6933
51.0k
        else
6934
51.0k
        {
6935
51.0k
            window->Collapsed = false;
6936
51.0k
        }
6937
159k
        window->WantCollapseToggle = false;
6938
6939
        // SIZE
6940
6941
        // Outer Decoration Sizes
6942
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6943
159k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6944
159k
        window->DecoOuterSizeX1 = 0.0f;
6945
159k
        window->DecoOuterSizeX2 = 0.0f;
6946
159k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6947
159k
        window->DecoOuterSizeY2 = 0.0f;
6948
159k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6949
6950
        // Calculate auto-fit size, handle automatic resize
6951
159k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6952
159k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6953
0
        {
6954
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6955
0
            if (!window_size_x_set_by_api)
6956
0
            {
6957
0
                window->SizeFull.x = size_auto_fit.x;
6958
0
                use_current_size_for_scrollbar_x = true;
6959
0
            }
6960
0
            if (!window_size_y_set_by_api)
6961
0
            {
6962
0
                window->SizeFull.y = size_auto_fit.y;
6963
0
                use_current_size_for_scrollbar_y = true;
6964
0
            }
6965
0
        }
6966
159k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6967
2
        {
6968
            // Auto-fit may only grow window during the first few frames
6969
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6970
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6971
2
            {
6972
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6973
2
                use_current_size_for_scrollbar_x = true;
6974
2
            }
6975
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6976
2
            {
6977
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6978
2
                use_current_size_for_scrollbar_y = true;
6979
2
            }
6980
2
            if (!window->Collapsed)
6981
2
                MarkIniSettingsDirty(window);
6982
2
        }
6983
6984
        // Apply minimum/maximum window size constraints and final size
6985
159k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6986
159k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6987
6988
        // POSITION
6989
6990
        // Popup latch its initial position, will position itself when it appears next frame
6991
159k
        if (window_just_activated_by_user)
6992
4
        {
6993
4
            window->AutoPosLastDirection = ImGuiDir_None;
6994
4
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6995
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6996
4
        }
6997
6998
        // Position child window
6999
159k
        if (flags & ImGuiWindowFlags_ChildWindow)
7000
51.0k
        {
7001
51.0k
            IM_ASSERT(parent_window && parent_window->Active);
7002
51.0k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7003
51.0k
            parent_window->DC.ChildWindows.push_back(window);
7004
51.0k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7005
51.0k
                window->Pos = parent_window->DC.CursorPos;
7006
51.0k
        }
7007
7008
159k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7009
159k
        if (window_pos_with_pivot)
7010
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7011
159k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7012
0
            window->Pos = FindBestWindowPosForPopup(window);
7013
159k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7014
0
            window->Pos = FindBestWindowPosForPopup(window);
7015
159k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7016
0
            window->Pos = FindBestWindowPosForPopup(window);
7017
7018
        // Late create viewport if we don't fit within our current host viewport.
7019
159k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7020
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7021
0
            {
7022
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7023
                //ImGuiViewport* old_viewport = window->Viewport;
7024
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7025
7026
                // FIXME-DPI
7027
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7028
0
                SetCurrentViewport(window, window->Viewport);
7029
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7030
0
                SetCurrentWindow(window);
7031
0
            }
7032
7033
159k
        if (window->ViewportOwned)
7034
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7035
7036
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7037
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7038
159k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7039
159k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7040
159k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7041
159k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7042
7043
        // Clamp position/size so window stays visible within its viewport or monitor
7044
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7045
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7046
159k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7047
108k
        {
7048
108k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7049
108k
            {
7050
108k
                ClampWindowPos(window, visibility_rect);
7051
108k
            }
7052
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7053
0
            {
7054
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7055
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7056
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7057
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7058
0
                ClampWindowPos(window, visibility_rect);
7059
0
            }
7060
108k
        }
7061
159k
        window->Pos = ImTrunc(window->Pos);
7062
7063
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7064
        // Large values tend to lead to variety of artifacts and are not recommended.
7065
159k
        if (window->ViewportOwned || window->DockIsActive)
7066
0
            window->WindowRounding = 0.0f;
7067
159k
        else
7068
159k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7069
7070
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7071
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7072
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7073
7074
        // Apply window focus (new and reactivated windows are moved to front)
7075
159k
        bool want_focus = false;
7076
159k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7077
4
        {
7078
4
            if (flags & ImGuiWindowFlags_Popup)
7079
0
                want_focus = true;
7080
4
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7081
2
                want_focus = true;
7082
4
        }
7083
7084
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7085
#ifdef IMGUI_ENABLE_TEST_ENGINE
7086
        if (g.TestEngineHookItems)
7087
        {
7088
            IM_ASSERT(window->IDStack.Size == 1);
7089
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7090
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7091
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7092
            window->IDStack.Size = 1;
7093
        }
7094
#endif
7095
7096
        // Decide if we are going to handle borders and resize grips
7097
159k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7098
7099
        // Handle manual resize: Resize Grips, Borders, Gamepad
7100
159k
        int border_held = -1;
7101
159k
        ImU32 resize_grip_col[4] = {};
7102
159k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7103
159k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7104
159k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7105
156k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7106
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
7107
159k
        window->ResizeBorderHeld = (signed char)border_held;
7108
7109
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7110
159k
        if (window->ViewportOwned)
7111
0
        {
7112
0
            if (!window->Viewport->PlatformRequestMove)
7113
0
                window->Viewport->Pos = window->Pos;
7114
0
            if (!window->Viewport->PlatformRequestResize)
7115
0
                window->Viewport->Size = window->Size;
7116
0
            window->Viewport->UpdateWorkRect();
7117
0
            viewport_rect = window->Viewport->GetMainRect();
7118
0
        }
7119
7120
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7121
159k
        window->ViewportPos = window->Viewport->Pos;
7122
7123
        // SCROLLBAR VISIBILITY
7124
7125
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7126
159k
        if (!window->Collapsed)
7127
156k
        {
7128
            // When reading the current size we need to read it after size constraints have been applied.
7129
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7130
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7131
156k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7132
156k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7133
156k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7134
156k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7135
156k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7136
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7137
156k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7138
156k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7139
156k
            if (window->ScrollbarX && !window->ScrollbarY)
7140
3.12k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7141
156k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7142
7143
            // Amend the partially filled window->DecorationXXX values.
7144
156k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7145
156k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7146
156k
        }
7147
7148
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7149
        // Update various regions. Variables they depend on should be set above in this function.
7150
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7151
7152
        // Outer rectangle
7153
        // Not affected by window border size. Used by:
7154
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7155
        // - Begin() initial clipping rect for drawing window background and borders.
7156
        // - Begin() clipping whole child
7157
159k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7158
159k
        const ImRect outer_rect = window->Rect();
7159
159k
        const ImRect title_bar_rect = window->TitleBarRect();
7160
159k
        window->OuterRectClipped = outer_rect;
7161
159k
        if (window->DockIsActive)
7162
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7163
159k
        window->OuterRectClipped.ClipWith(host_rect);
7164
7165
        // Inner rectangle
7166
        // Not affected by window border size. Used by:
7167
        // - InnerClipRect
7168
        // - ScrollToRectEx()
7169
        // - NavUpdatePageUpPageDown()
7170
        // - Scrollbar()
7171
159k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7172
159k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7173
159k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7174
159k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7175
7176
        // Inner clipping rectangle.
7177
        // Will extend a little bit outside the normal work region.
7178
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7179
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7180
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7181
        // Affected by window/frame border size. Used by:
7182
        // - Begin() initial clip rect
7183
159k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7184
159k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7185
159k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7186
159k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7187
159k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7188
159k
        window->InnerClipRect.ClipWithFull(host_rect);
7189
7190
        // Default item width. Make it proportional to window size if window manually resizes
7191
159k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7192
159k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7193
0
        else
7194
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7195
7196
        // SCROLLING
7197
7198
        // Lock down maximum scrolling
7199
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7200
        // for right/bottom aligned items without creating a scrollbar.
7201
159k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7202
159k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7203
7204
        // Apply scrolling
7205
159k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7206
159k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7207
159k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7208
7209
        // DRAWING
7210
7211
        // Setup draw list and outer clipping rectangle
7212
159k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7213
159k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7214
159k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7215
7216
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7217
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7218
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7219
159k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7220
159k
        if (is_undocked_or_docked_visible)
7221
159k
        {
7222
159k
            bool render_decorations_in_parent = false;
7223
159k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7224
51.0k
            {
7225
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7226
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7227
51.0k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7228
51.0k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7229
51.0k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7230
51.0k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7231
51.0k
                    render_decorations_in_parent = true;
7232
51.0k
            }
7233
159k
            if (render_decorations_in_parent)
7234
51.0k
                window->DrawList = parent_window->DrawList;
7235
7236
            // Handle title bar, scrollbar, resize grips and resize borders
7237
159k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7238
159k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7239
159k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7240
7241
159k
            if (render_decorations_in_parent)
7242
51.0k
                window->DrawList = &window->DrawListInst;
7243
159k
        }
7244
7245
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7246
7247
        // Work rectangle.
7248
        // Affected by window padding and border size. Used by:
7249
        // - Columns() for right-most edge
7250
        // - TreeNode(), CollapsingHeader() for right-most edge
7251
        // - BeginTabBar() for right-most edge
7252
159k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7253
159k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7254
159k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7255
159k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7256
159k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7257
159k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7258
159k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7259
159k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7260
159k
        window->ParentWorkRect = window->WorkRect;
7261
7262
        // [LEGACY] Content Region
7263
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7264
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7265
        // Used by:
7266
        // - Mouse wheel scrolling + many other things
7267
159k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7268
159k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7269
159k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7270
159k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7271
7272
        // Setup drawing context
7273
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7274
159k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7275
159k
        window->DC.GroupOffset.x = 0.0f;
7276
159k
        window->DC.ColumnsOffset.x = 0.0f;
7277
7278
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7279
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7280
159k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7281
159k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7282
159k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7283
159k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7284
159k
        window->DC.CursorPos = window->DC.CursorStartPos;
7285
159k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7286
159k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7287
159k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7288
159k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7289
159k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7290
159k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7291
7292
159k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7293
159k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7294
159k
        window->DC.NavLayersActiveMaskNext = 0x00;
7295
159k
        window->DC.NavIsScrollPushableX = true;
7296
159k
        window->DC.NavHideHighlightOneFrame = false;
7297
159k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7298
7299
159k
        window->DC.MenuBarAppending = false;
7300
159k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7301
159k
        window->DC.TreeDepth = 0;
7302
159k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7303
159k
        window->DC.ChildWindows.resize(0);
7304
159k
        window->DC.StateStorage = &window->StateStorage;
7305
159k
        window->DC.CurrentColumns = NULL;
7306
159k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7307
159k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7308
7309
159k
        window->DC.ItemWidth = window->ItemWidthDefault;
7310
159k
        window->DC.TextWrapPos = -1.0f; // disabled
7311
159k
        window->DC.ItemWidthStack.resize(0);
7312
159k
        window->DC.TextWrapPosStack.resize(0);
7313
7314
159k
        if (window->AutoFitFramesX > 0)
7315
2
            window->AutoFitFramesX--;
7316
159k
        if (window->AutoFitFramesY > 0)
7317
2
            window->AutoFitFramesY--;
7318
7319
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7320
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7321
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7322
        // - Position window behind the modal that is not a begin-parent of this window.
7323
159k
        if (want_focus)
7324
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7325
159k
        if (want_focus && window == g.NavWindow)
7326
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7327
7328
        // Close requested by platform window (apply to all windows in this viewport)
7329
159k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7330
0
        {
7331
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7332
0
            *p_open = false;
7333
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7334
0
        }
7335
7336
        // Title bar
7337
159k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7338
108k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7339
7340
        // Clear hit test shape every frame
7341
159k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7342
7343
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7344
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7345
        // Maybe we can support CTRL+C on every element?
7346
        /*
7347
        //if (g.NavWindow == window && g.ActiveId == 0)
7348
        if (g.ActiveId == window->MoveId)
7349
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7350
                LogToClipboard();
7351
        */
7352
7353
159k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7354
159k
        {
7355
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7356
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7357
159k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7358
30
                BeginDockableDragDropSource(window);
7359
7360
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7361
159k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7362
12
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7363
9
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7364
9
                        BeginDockableDragDropTarget(window);
7365
159k
        }
7366
7367
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7368
        // This is useful to allow creating context menus on title bar only, etc.
7369
159k
        if (window->DockIsActive)
7370
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7371
159k
        else
7372
159k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7373
7374
        // [DEBUG]
7375
159k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7376
159k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7377
0
            DebugLocateItemResolveWithLastItem();
7378
159k
#endif
7379
7380
        // [Test Engine] Register title bar / tab with MoveId.
7381
#ifdef IMGUI_ENABLE_TEST_ENGINE
7382
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7383
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7384
#endif
7385
159k
    }
7386
0
    else
7387
0
    {
7388
        // Append
7389
0
        SetCurrentViewport(window, window->Viewport);
7390
0
        SetCurrentWindow(window);
7391
0
    }
7392
7393
159k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7394
159k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7395
7396
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7397
159k
    window->WriteAccessed = false;
7398
159k
    window->BeginCount++;
7399
159k
    g.NextWindowData.ClearFlags();
7400
7401
    // Update visibility
7402
159k
    if (first_begin_of_the_frame)
7403
159k
    {
7404
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7405
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7406
        // This is analogous to regular windows being hidden from one frame.
7407
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7408
159k
        if (window->DockIsActive && !window->DockTabIsVisible)
7409
0
        {
7410
0
            if (window->LastFrameJustFocused == g.FrameCount)
7411
0
                window->HiddenFramesCannotSkipItems = 1;
7412
0
            else
7413
0
                window->HiddenFramesCanSkipItems = 1;
7414
0
        }
7415
7416
159k
        if (flags & ImGuiWindowFlags_ChildWindow)
7417
51.0k
        {
7418
            // Child window can be out of sight and have "negative" clip windows.
7419
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7420
51.0k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7421
51.0k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7422
51.0k
            {
7423
51.0k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7424
51.0k
                if (!g.LogEnabled && !nav_request)
7425
51.0k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7426
0
                        window->HiddenFramesCanSkipItems = 1;
7427
51.0k
            }
7428
7429
            // Hide along with parent or if parent is collapsed
7430
51.0k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7431
0
                window->HiddenFramesCanSkipItems = 1;
7432
51.0k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7433
1
                window->HiddenFramesCannotSkipItems = 1;
7434
51.0k
        }
7435
7436
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7437
159k
        if (style.Alpha <= 0.0f)
7438
0
            window->HiddenFramesCanSkipItems = 1;
7439
7440
        // Update the Hidden flag
7441
159k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7442
159k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7443
7444
        // Disable inputs for requested number of frames
7445
159k
        if (window->DisableInputsFrames > 0)
7446
0
        {
7447
0
            window->DisableInputsFrames--;
7448
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7449
0
        }
7450
7451
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7452
159k
        bool skip_items = false;
7453
159k
        if (window->Collapsed || !window->Active || hidden_regular)
7454
3.13k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7455
3.12k
                skip_items = true;
7456
159k
        window->SkipItems = skip_items;
7457
7458
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7459
159k
        if (window->SkipItems)
7460
3.12k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7461
7462
        // Sanity check: there are two spots which can set Appearing = true
7463
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7464
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7465
159k
        if (window->SkipItems && !window->Appearing)
7466
159k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7467
159k
    }
7468
7469
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7470
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7471
159k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7472
0
    {
7473
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7474
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7475
0
        return false;
7476
0
    }
7477
7478
159k
    return !window->SkipItems;
7479
159k
}
7480
7481
void ImGui::End()
7482
159k
{
7483
159k
    ImGuiContext& g = *GImGui;
7484
159k
    ImGuiWindow* window = g.CurrentWindow;
7485
7486
    // Error checking: verify that user hasn't called End() too many times!
7487
159k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7488
0
    {
7489
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7490
0
        return;
7491
0
    }
7492
159k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7493
7494
    // Error checking: verify that user doesn't directly call End() on a child window.
7495
159k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7496
159k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7497
7498
    // Close anything that is open
7499
159k
    if (window->DC.CurrentColumns)
7500
0
        EndColumns();
7501
159k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7502
159k
        PopClipRect();
7503
159k
    PopFocusScope();
7504
7505
    // Stop logging
7506
159k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7507
108k
        LogFinish();
7508
7509
159k
    if (window->DC.IsSetPos)
7510
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7511
7512
    // Docking: report contents sizes to parent to allow for auto-resize
7513
159k
    if (window->DockNode && window->DockTabIsVisible)
7514
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7515
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7516
7517
    // Pop from window stack
7518
159k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7519
159k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7520
0
        g.BeginMenuCount--;
7521
159k
    if (window->Flags & ImGuiWindowFlags_Popup)
7522
0
        g.BeginPopupStack.pop_back();
7523
159k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7524
159k
    g.CurrentWindowStack.pop_back();
7525
159k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7526
159k
    if (g.CurrentWindow)
7527
105k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7528
159k
}
7529
7530
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7531
23.1k
{
7532
23.1k
    ImGuiContext& g = *GImGui;
7533
23.1k
    IM_ASSERT(window == window->RootWindow);
7534
7535
23.1k
    const int cur_order = window->FocusOrder;
7536
23.1k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7537
23.1k
    if (g.WindowsFocusOrder.back() == window)
7538
23.1k
        return;
7539
7540
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7541
0
    for (int n = cur_order; n < new_order; n++)
7542
0
    {
7543
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7544
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7545
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7546
0
    }
7547
0
    g.WindowsFocusOrder[new_order] = window;
7548
0
    window->FocusOrder = (short)new_order;
7549
0
}
7550
7551
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7552
23.1k
{
7553
23.1k
    ImGuiContext& g = *GImGui;
7554
23.1k
    ImGuiWindow* current_front_window = g.Windows.back();
7555
23.1k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7556
23.1k
        return;
7557
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7558
0
        if (g.Windows[i] == window)
7559
0
        {
7560
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7561
0
            g.Windows[g.Windows.Size - 1] = window;
7562
0
            break;
7563
0
        }
7564
0
}
7565
7566
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7567
0
{
7568
0
    ImGuiContext& g = *GImGui;
7569
0
    if (g.Windows[0] == window)
7570
0
        return;
7571
0
    for (int i = 0; i < g.Windows.Size; i++)
7572
0
        if (g.Windows[i] == window)
7573
0
        {
7574
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7575
0
            g.Windows[0] = window;
7576
0
            break;
7577
0
        }
7578
0
}
7579
7580
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7581
0
{
7582
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7583
0
    ImGuiContext& g = *GImGui;
7584
0
    window = window->RootWindow;
7585
0
    behind_window = behind_window->RootWindow;
7586
0
    int pos_wnd = FindWindowDisplayIndex(window);
7587
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7588
0
    if (pos_wnd < pos_beh)
7589
0
    {
7590
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7591
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7592
0
        g.Windows[pos_beh - 1] = window;
7593
0
    }
7594
0
    else
7595
0
    {
7596
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7597
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7598
0
        g.Windows[pos_beh] = window;
7599
0
    }
7600
0
}
7601
7602
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7603
0
{
7604
0
    ImGuiContext& g = *GImGui;
7605
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7606
0
}
7607
7608
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7609
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7610
33.6k
{
7611
33.6k
    ImGuiContext& g = *GImGui;
7612
7613
    // Modal check?
7614
33.6k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7615
1.24k
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7616
0
        {
7617
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7618
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7619
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7620
0
            return;
7621
0
        }
7622
7623
    // Find last focused child (if any) and focus it instead.
7624
33.6k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7625
0
        window = NavRestoreLastChildNavWindow(window);
7626
7627
    // Apply focus
7628
33.6k
    if (g.NavWindow != window)
7629
12.6k
    {
7630
12.6k
        SetNavWindow(window);
7631
12.6k
        if (window && g.NavDisableMouseHover)
7632
1.18k
            g.NavMousePosDirty = true;
7633
12.6k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7634
12.6k
        g.NavLayer = ImGuiNavLayer_Main;
7635
12.6k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7636
12.6k
        g.NavIdIsAlive = false;
7637
12.6k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7638
7639
        // Close popups if any
7640
12.6k
        ClosePopupsOverWindow(window, false);
7641
12.6k
    }
7642
7643
    // Move the root window to the top of the pile
7644
33.6k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7645
33.6k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7646
33.6k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7647
33.6k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7648
33.6k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7649
7650
    // Steal active widgets. Some of the cases it triggers includes:
7651
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7652
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7653
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7654
33.6k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7655
21
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7656
8
            ClearActiveID();
7657
7658
    // Passing NULL allow to disable keyboard focus
7659
33.6k
    if (!window)
7660
10.4k
        return;
7661
23.1k
    window->LastFrameJustFocused = g.FrameCount;
7662
7663
    // Select in dock node
7664
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7665
    //if (dock_node && dock_node->TabBar)
7666
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7667
7668
    // Bring to front
7669
23.1k
    BringWindowToFocusFront(focus_front_window);
7670
23.1k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7671
23.1k
        BringWindowToDisplayFront(display_front_window);
7672
23.1k
}
7673
7674
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7675
0
{
7676
0
    ImGuiContext& g = *GImGui;
7677
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7678
0
    if (under_this_window != NULL)
7679
0
    {
7680
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7681
0
        int offset = -1;
7682
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7683
0
        {
7684
0
            under_this_window = under_this_window->ParentWindow;
7685
0
            offset = 0;
7686
0
        }
7687
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7688
0
    }
7689
0
    for (int i = start_idx; i >= 0; i--)
7690
0
    {
7691
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7692
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7693
0
        IM_ASSERT(window == window->RootWindow);
7694
0
        if (window == ignore_window || !window->WasActive)
7695
0
            continue;
7696
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7697
0
            continue;
7698
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7699
0
        {
7700
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7701
            // This is failing (lagging by one frame) for docked windows.
7702
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7703
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7704
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7705
0
            FocusWindow(window, flags);
7706
0
            return;
7707
0
        }
7708
0
    }
7709
0
    FocusWindow(NULL, flags);
7710
0
}
7711
7712
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7713
void ImGui::SetCurrentFont(ImFont* font)
7714
54.1k
{
7715
54.1k
    ImGuiContext& g = *GImGui;
7716
54.1k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7717
54.1k
    IM_ASSERT(font->Scale > 0.0f);
7718
54.1k
    g.Font = font;
7719
54.1k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7720
54.1k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7721
7722
54.1k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7723
54.1k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7724
54.1k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7725
54.1k
    g.DrawListSharedData.Font = g.Font;
7726
54.1k
    g.DrawListSharedData.FontSize = g.FontSize;
7727
54.1k
}
7728
7729
void ImGui::PushFont(ImFont* font)
7730
0
{
7731
0
    ImGuiContext& g = *GImGui;
7732
0
    if (!font)
7733
0
        font = GetDefaultFont();
7734
0
    SetCurrentFont(font);
7735
0
    g.FontStack.push_back(font);
7736
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7737
0
}
7738
7739
void  ImGui::PopFont()
7740
0
{
7741
0
    ImGuiContext& g = *GImGui;
7742
0
    g.CurrentWindow->DrawList->PopTextureID();
7743
0
    g.FontStack.pop_back();
7744
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7745
0
}
7746
7747
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7748
51.0k
{
7749
51.0k
    ImGuiContext& g = *GImGui;
7750
51.0k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7751
51.0k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7752
51.0k
    if (enabled)
7753
0
        item_flags |= option;
7754
51.0k
    else
7755
51.0k
        item_flags &= ~option;
7756
51.0k
    g.CurrentItemFlags = item_flags;
7757
51.0k
    g.ItemFlagsStack.push_back(item_flags);
7758
51.0k
}
7759
7760
void ImGui::PopItemFlag()
7761
51.0k
{
7762
51.0k
    ImGuiContext& g = *GImGui;
7763
51.0k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7764
51.0k
    g.ItemFlagsStack.pop_back();
7765
51.0k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7766
51.0k
}
7767
7768
// BeginDisabled()/EndDisabled()
7769
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7770
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7771
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7772
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7773
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7774
void ImGui::BeginDisabled(bool disabled)
7775
0
{
7776
0
    ImGuiContext& g = *GImGui;
7777
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7778
0
    if (!was_disabled && disabled)
7779
0
    {
7780
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7781
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7782
0
    }
7783
0
    if (was_disabled || disabled)
7784
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7785
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7786
0
    g.DisabledStackSize++;
7787
0
}
7788
7789
void ImGui::EndDisabled()
7790
0
{
7791
0
    ImGuiContext& g = *GImGui;
7792
0
    IM_ASSERT(g.DisabledStackSize > 0);
7793
0
    g.DisabledStackSize--;
7794
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7795
    //PopItemFlag();
7796
0
    g.ItemFlagsStack.pop_back();
7797
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7798
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7799
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7800
0
}
7801
7802
void ImGui::PushTabStop(bool tab_stop)
7803
51.0k
{
7804
51.0k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7805
51.0k
}
7806
7807
void ImGui::PopTabStop()
7808
51.0k
{
7809
51.0k
    PopItemFlag();
7810
51.0k
}
7811
7812
void ImGui::PushButtonRepeat(bool repeat)
7813
0
{
7814
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7815
0
}
7816
7817
void ImGui::PopButtonRepeat()
7818
0
{
7819
0
    PopItemFlag();
7820
0
}
7821
7822
void ImGui::PushTextWrapPos(float wrap_pos_x)
7823
0
{
7824
0
    ImGuiWindow* window = GetCurrentWindow();
7825
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7826
0
    window->DC.TextWrapPos = wrap_pos_x;
7827
0
}
7828
7829
void ImGui::PopTextWrapPos()
7830
0
{
7831
0
    ImGuiWindow* window = GetCurrentWindow();
7832
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7833
0
    window->DC.TextWrapPosStack.pop_back();
7834
0
}
7835
7836
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7837
0
{
7838
0
    ImGuiWindow* last_window = NULL;
7839
0
    while (last_window != window)
7840
0
    {
7841
0
        last_window = window;
7842
0
        window = window->RootWindow;
7843
0
        if (popup_hierarchy)
7844
0
            window = window->RootWindowPopupTree;
7845
0
    if (dock_hierarchy)
7846
0
      window = window->RootWindowDockTree;
7847
0
  }
7848
0
    return window;
7849
0
}
7850
7851
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7852
0
{
7853
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7854
0
    if (window_root == potential_parent)
7855
0
        return true;
7856
0
    while (window != NULL)
7857
0
    {
7858
0
        if (window == potential_parent)
7859
0
            return true;
7860
0
        if (window == window_root) // end of chain
7861
0
            return false;
7862
0
        window = window->ParentWindow;
7863
0
    }
7864
0
    return false;
7865
0
}
7866
7867
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7868
0
{
7869
0
    if (window->RootWindow == potential_parent)
7870
0
        return true;
7871
0
    while (window != NULL)
7872
0
    {
7873
0
        if (window == potential_parent)
7874
0
            return true;
7875
0
        window = window->ParentWindowInBeginStack;
7876
0
    }
7877
0
    return false;
7878
0
}
7879
7880
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7881
0
{
7882
0
    ImGuiContext& g = *GImGui;
7883
7884
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7885
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7886
0
    if (display_layer_delta != 0)
7887
0
        return display_layer_delta > 0;
7888
7889
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7890
0
    {
7891
0
        ImGuiWindow* candidate_window = g.Windows[i];
7892
0
        if (candidate_window == potential_above)
7893
0
            return true;
7894
0
        if (candidate_window == potential_below)
7895
0
            return false;
7896
0
    }
7897
0
    return false;
7898
0
}
7899
7900
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7901
85.2k
{
7902
85.2k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
7903
7904
85.2k
    ImGuiContext& g = *GImGui;
7905
85.2k
    ImGuiWindow* ref_window = g.HoveredWindow;
7906
85.2k
    ImGuiWindow* cur_window = g.CurrentWindow;
7907
85.2k
    if (ref_window == NULL)
7908
83.4k
        return false;
7909
7910
1.74k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7911
1.74k
    {
7912
1.74k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7913
1.74k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7914
1.74k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7915
1.74k
        if (flags & ImGuiHoveredFlags_RootWindow)
7916
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7917
7918
1.74k
        bool result;
7919
1.74k
        if (flags & ImGuiHoveredFlags_ChildWindows)
7920
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7921
1.74k
        else
7922
1.74k
            result = (ref_window == cur_window);
7923
1.74k
        if (!result)
7924
1.74k
            return false;
7925
1.74k
    }
7926
7927
1
    if (!IsWindowContentHoverable(ref_window, flags))
7928
0
        return false;
7929
1
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7930
1
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7931
0
            return false;
7932
7933
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
7934
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
7935
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
7936
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
7937
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
7938
1
    if (flags & ImGuiHoveredFlags_ForTooltip)
7939
0
        flags |= g.Style.HoverFlagsForTooltipMouse;
7940
1
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
7941
0
        return false;
7942
7943
1
    return true;
7944
1
}
7945
7946
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7947
98.4k
{
7948
98.4k
    ImGuiContext& g = *GImGui;
7949
98.4k
    ImGuiWindow* ref_window = g.NavWindow;
7950
98.4k
    ImGuiWindow* cur_window = g.CurrentWindow;
7951
7952
98.4k
    if (ref_window == NULL)
7953
26.1k
        return false;
7954
72.3k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7955
0
        return true;
7956
7957
72.3k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7958
72.3k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7959
72.3k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7960
72.3k
    if (flags & ImGuiHoveredFlags_RootWindow)
7961
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7962
7963
72.3k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7964
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7965
72.3k
    else
7966
72.3k
        return (ref_window == cur_window);
7967
72.3k
}
7968
7969
ImGuiID ImGui::GetWindowDockID()
7970
0
{
7971
0
    ImGuiContext& g = *GImGui;
7972
0
    return g.CurrentWindow->DockId;
7973
0
}
7974
7975
bool ImGui::IsWindowDocked()
7976
0
{
7977
0
    ImGuiContext& g = *GImGui;
7978
0
    return g.CurrentWindow->DockIsActive;
7979
0
}
7980
7981
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7982
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7983
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7984
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7985
0
{
7986
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7987
0
}
7988
7989
float ImGui::GetWindowWidth()
7990
22.7k
{
7991
22.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
7992
22.7k
    return window->Size.x;
7993
22.7k
}
7994
7995
float ImGui::GetWindowHeight()
7996
24.2k
{
7997
24.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
7998
24.2k
    return window->Size.y;
7999
24.2k
}
8000
8001
ImVec2 ImGui::GetWindowPos()
8002
0
{
8003
0
    ImGuiContext& g = *GImGui;
8004
0
    ImGuiWindow* window = g.CurrentWindow;
8005
0
    return window->Pos;
8006
0
}
8007
8008
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8009
7
{
8010
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8011
7
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8012
0
        return;
8013
8014
7
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8015
7
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8016
7
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8017
8018
    // Set
8019
7
    const ImVec2 old_pos = window->Pos;
8020
7
    window->Pos = ImTrunc(pos);
8021
7
    ImVec2 offset = window->Pos - old_pos;
8022
7
    if (offset.x == 0.0f && offset.y == 0.0f)
8023
0
        return;
8024
7
    MarkIniSettingsDirty(window);
8025
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8026
7
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8027
7
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8028
7
    window->DC.IdealMaxPos += offset;
8029
7
    window->DC.CursorStartPos += offset;
8030
7
}
8031
8032
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8033
0
{
8034
0
    ImGuiWindow* window = GetCurrentWindowRead();
8035
0
    SetWindowPos(window, pos, cond);
8036
0
}
8037
8038
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8039
0
{
8040
0
    if (ImGuiWindow* window = FindWindowByName(name))
8041
0
        SetWindowPos(window, pos, cond);
8042
0
}
8043
8044
ImVec2 ImGui::GetWindowSize()
8045
0
{
8046
0
    ImGuiWindow* window = GetCurrentWindowRead();
8047
0
    return window->Size;
8048
0
}
8049
8050
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8051
105k
{
8052
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8053
105k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8054
54.1k
        return;
8055
8056
51.0k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8057
51.0k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8058
8059
    // Set
8060
51.0k
    ImVec2 old_size = window->SizeFull;
8061
51.0k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8062
51.0k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8063
51.0k
    if (size.x <= 0.0f)
8064
0
        window->AutoFitOnlyGrows = false;
8065
51.0k
    else
8066
51.0k
        window->SizeFull.x = IM_TRUNC(size.x);
8067
51.0k
    if (size.y <= 0.0f)
8068
0
        window->AutoFitOnlyGrows = false;
8069
51.0k
    else
8070
51.0k
        window->SizeFull.y = IM_TRUNC(size.y);
8071
51.0k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8072
9.31k
        MarkIniSettingsDirty(window);
8073
51.0k
}
8074
8075
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8076
0
{
8077
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8078
0
}
8079
8080
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8081
0
{
8082
0
    if (ImGuiWindow* window = FindWindowByName(name))
8083
0
        SetWindowSize(window, size, cond);
8084
0
}
8085
8086
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8087
0
{
8088
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8089
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8090
0
        return;
8091
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8092
8093
    // Set
8094
0
    window->Collapsed = collapsed;
8095
0
}
8096
8097
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8098
0
{
8099
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8100
0
    window->HitTestHoleSize = ImVec2ih(size);
8101
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8102
0
}
8103
8104
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8105
0
{
8106
0
    window->Hidden = window->SkipItems = true;
8107
0
    window->HiddenFramesCanSkipItems = 1;
8108
0
}
8109
8110
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8111
0
{
8112
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8113
0
}
8114
8115
bool ImGui::IsWindowCollapsed()
8116
0
{
8117
0
    ImGuiWindow* window = GetCurrentWindowRead();
8118
0
    return window->Collapsed;
8119
0
}
8120
8121
bool ImGui::IsWindowAppearing()
8122
0
{
8123
0
    ImGuiWindow* window = GetCurrentWindowRead();
8124
0
    return window->Appearing;
8125
0
}
8126
8127
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8128
0
{
8129
0
    if (ImGuiWindow* window = FindWindowByName(name))
8130
0
        SetWindowCollapsed(window, collapsed, cond);
8131
0
}
8132
8133
void ImGui::SetWindowFocus()
8134
22.7k
{
8135
22.7k
    FocusWindow(GImGui->CurrentWindow);
8136
22.7k
}
8137
8138
void ImGui::SetWindowFocus(const char* name)
8139
0
{
8140
0
    if (name)
8141
0
    {
8142
0
        if (ImGuiWindow* window = FindWindowByName(name))
8143
0
            FocusWindow(window);
8144
0
    }
8145
0
    else
8146
0
    {
8147
0
        FocusWindow(NULL);
8148
0
    }
8149
0
}
8150
8151
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8152
0
{
8153
0
    ImGuiContext& g = *GImGui;
8154
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8155
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8156
0
    g.NextWindowData.PosVal = pos;
8157
0
    g.NextWindowData.PosPivotVal = pivot;
8158
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8159
0
    g.NextWindowData.PosUndock = true;
8160
0
}
8161
8162
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8163
105k
{
8164
105k
    ImGuiContext& g = *GImGui;
8165
105k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8166
105k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8167
105k
    g.NextWindowData.SizeVal = size;
8168
105k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8169
105k
}
8170
8171
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8172
0
{
8173
0
    ImGuiContext& g = *GImGui;
8174
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8175
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8176
0
    g.NextWindowData.SizeCallback = custom_callback;
8177
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8178
0
}
8179
8180
// Content size = inner scrollable rectangle, padded with WindowPadding.
8181
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8182
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8183
0
{
8184
0
    ImGuiContext& g = *GImGui;
8185
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8186
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8187
0
}
8188
8189
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8190
0
{
8191
0
    ImGuiContext& g = *GImGui;
8192
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8193
0
    g.NextWindowData.ScrollVal = scroll;
8194
0
}
8195
8196
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8197
0
{
8198
0
    ImGuiContext& g = *GImGui;
8199
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8200
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8201
0
    g.NextWindowData.CollapsedVal = collapsed;
8202
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8203
0
}
8204
8205
void ImGui::SetNextWindowFocus()
8206
0
{
8207
0
    ImGuiContext& g = *GImGui;
8208
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8209
0
}
8210
8211
void ImGui::SetNextWindowBgAlpha(float alpha)
8212
0
{
8213
0
    ImGuiContext& g = *GImGui;
8214
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8215
0
    g.NextWindowData.BgAlphaVal = alpha;
8216
0
}
8217
8218
void ImGui::SetNextWindowViewport(ImGuiID id)
8219
0
{
8220
0
    ImGuiContext& g = *GImGui;
8221
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8222
0
    g.NextWindowData.ViewportId = id;
8223
0
}
8224
8225
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8226
0
{
8227
0
    ImGuiContext& g = *GImGui;
8228
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8229
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8230
0
    g.NextWindowData.DockId = id;
8231
0
}
8232
8233
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8234
0
{
8235
0
    ImGuiContext& g = *GImGui;
8236
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8237
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8238
0
    g.NextWindowData.WindowClass = *window_class;
8239
0
}
8240
8241
ImDrawList* ImGui::GetWindowDrawList()
8242
51.0k
{
8243
51.0k
    ImGuiWindow* window = GetCurrentWindow();
8244
51.0k
    return window->DrawList;
8245
51.0k
}
8246
8247
float ImGui::GetWindowDpiScale()
8248
0
{
8249
0
    ImGuiContext& g = *GImGui;
8250
0
    return g.CurrentDpiScale;
8251
0
}
8252
8253
ImGuiViewport* ImGui::GetWindowViewport()
8254
0
{
8255
0
    ImGuiContext& g = *GImGui;
8256
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8257
0
    return g.CurrentViewport;
8258
0
}
8259
8260
ImFont* ImGui::GetFont()
8261
24.2M
{
8262
24.2M
    return GImGui->Font;
8263
24.2M
}
8264
8265
float ImGui::GetFontSize()
8266
24.2M
{
8267
24.2M
    return GImGui->FontSize;
8268
24.2M
}
8269
8270
ImVec2 ImGui::GetFontTexUvWhitePixel()
8271
0
{
8272
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8273
0
}
8274
8275
void ImGui::SetWindowFontScale(float scale)
8276
0
{
8277
0
    IM_ASSERT(scale > 0.0f);
8278
0
    ImGuiContext& g = *GImGui;
8279
0
    ImGuiWindow* window = GetCurrentWindow();
8280
0
    window->FontWindowScale = scale;
8281
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8282
0
}
8283
8284
void ImGui::PushFocusScope(ImGuiID id)
8285
159k
{
8286
159k
    ImGuiContext& g = *GImGui;
8287
159k
    g.FocusScopeStack.push_back(id);
8288
159k
    g.CurrentFocusScopeId = id;
8289
159k
}
8290
8291
void ImGui::PopFocusScope()
8292
159k
{
8293
159k
    ImGuiContext& g = *GImGui;
8294
159k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8295
159k
    g.FocusScopeStack.pop_back();
8296
159k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8297
159k
}
8298
8299
// Focus = move navigation cursor, set scrolling, set focus window.
8300
void ImGui::FocusItem()
8301
0
{
8302
0
    ImGuiContext& g = *GImGui;
8303
0
    ImGuiWindow* window = g.CurrentWindow;
8304
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8305
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8306
0
    {
8307
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8308
0
        return;
8309
0
    }
8310
8311
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8312
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8313
0
    SetNavWindow(window);
8314
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8315
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8316
0
}
8317
8318
void ImGui::ActivateItemByID(ImGuiID id)
8319
0
{
8320
0
    ImGuiContext& g = *GImGui;
8321
0
    g.NavNextActivateId = id;
8322
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8323
0
}
8324
8325
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8326
// But ActivateItem() should function without altering scroll/focus?
8327
void ImGui::SetKeyboardFocusHere(int offset)
8328
0
{
8329
0
    ImGuiContext& g = *GImGui;
8330
0
    ImGuiWindow* window = g.CurrentWindow;
8331
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8332
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8333
8334
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8335
    // When we refactor this function into ActivateItem() we may want to make this an option.
8336
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8337
    // is also automatically dropped in the event g.ActiveId is stolen.
8338
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8339
0
    {
8340
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8341
0
        return;
8342
0
    }
8343
8344
0
    SetNavWindow(window);
8345
8346
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8347
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8348
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8349
0
    if (offset == -1)
8350
0
    {
8351
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8352
0
    }
8353
0
    else
8354
0
    {
8355
0
        g.NavTabbingDir = 1;
8356
0
        g.NavTabbingCounter = offset + 1;
8357
0
    }
8358
0
}
8359
8360
void ImGui::SetItemDefaultFocus()
8361
0
{
8362
0
    ImGuiContext& g = *GImGui;
8363
0
    ImGuiWindow* window = g.CurrentWindow;
8364
0
    if (!window->Appearing)
8365
0
        return;
8366
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8367
0
        return;
8368
8369
0
    g.NavInitRequest = false;
8370
0
    NavApplyItemToResult(&g.NavInitResult);
8371
0
    NavUpdateAnyRequestFlag();
8372
8373
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8374
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8375
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8376
0
}
8377
8378
void ImGui::SetStateStorage(ImGuiStorage* tree)
8379
0
{
8380
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8381
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8382
0
}
8383
8384
ImGuiStorage* ImGui::GetStateStorage()
8385
0
{
8386
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8387
0
    return window->DC.StateStorage;
8388
0
}
8389
8390
void ImGui::PushID(const char* str_id)
8391
51.0k
{
8392
51.0k
    ImGuiContext& g = *GImGui;
8393
51.0k
    ImGuiWindow* window = g.CurrentWindow;
8394
51.0k
    ImGuiID id = window->GetID(str_id);
8395
51.0k
    window->IDStack.push_back(id);
8396
51.0k
}
8397
8398
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8399
0
{
8400
0
    ImGuiContext& g = *GImGui;
8401
0
    ImGuiWindow* window = g.CurrentWindow;
8402
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8403
0
    window->IDStack.push_back(id);
8404
0
}
8405
8406
void ImGui::PushID(const void* ptr_id)
8407
0
{
8408
0
    ImGuiContext& g = *GImGui;
8409
0
    ImGuiWindow* window = g.CurrentWindow;
8410
0
    ImGuiID id = window->GetID(ptr_id);
8411
0
    window->IDStack.push_back(id);
8412
0
}
8413
8414
void ImGui::PushID(int int_id)
8415
0
{
8416
0
    ImGuiContext& g = *GImGui;
8417
0
    ImGuiWindow* window = g.CurrentWindow;
8418
0
    ImGuiID id = window->GetID(int_id);
8419
0
    window->IDStack.push_back(id);
8420
0
}
8421
8422
// Push a given id value ignoring the ID stack as a seed.
8423
void ImGui::PushOverrideID(ImGuiID id)
8424
0
{
8425
0
    ImGuiContext& g = *GImGui;
8426
0
    ImGuiWindow* window = g.CurrentWindow;
8427
0
    if (g.DebugHookIdInfo == id)
8428
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8429
0
    window->IDStack.push_back(id);
8430
0
}
8431
8432
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8433
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8434
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8435
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8436
0
{
8437
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8438
0
    ImGuiContext& g = *GImGui;
8439
0
    if (g.DebugHookIdInfo == id)
8440
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8441
0
    return id;
8442
0
}
8443
8444
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8445
0
{
8446
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8447
0
    ImGuiContext& g = *GImGui;
8448
0
    if (g.DebugHookIdInfo == id)
8449
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8450
0
    return id;
8451
0
}
8452
8453
void ImGui::PopID()
8454
51.0k
{
8455
51.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
8456
51.0k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8457
51.0k
    window->IDStack.pop_back();
8458
51.0k
}
8459
8460
ImGuiID ImGui::GetID(const char* str_id)
8461
0
{
8462
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8463
0
    return window->GetID(str_id);
8464
0
}
8465
8466
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8467
0
{
8468
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8469
0
    return window->GetID(str_id_begin, str_id_end);
8470
0
}
8471
8472
ImGuiID ImGui::GetID(const void* ptr_id)
8473
0
{
8474
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8475
0
    return window->GetID(ptr_id);
8476
0
}
8477
8478
bool ImGui::IsRectVisible(const ImVec2& size)
8479
0
{
8480
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8481
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8482
0
}
8483
8484
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8485
0
{
8486
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8487
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8488
0
}
8489
8490
8491
//-----------------------------------------------------------------------------
8492
// [SECTION] INPUTS
8493
//-----------------------------------------------------------------------------
8494
// - GetKeyData() [Internal]
8495
// - GetKeyIndex() [Internal]
8496
// - GetKeyName()
8497
// - GetKeyChordName() [Internal]
8498
// - CalcTypematicRepeatAmount() [Internal]
8499
// - GetTypematicRepeatRate() [Internal]
8500
// - GetKeyPressedAmount() [Internal]
8501
// - GetKeyMagnitude2d() [Internal]
8502
//-----------------------------------------------------------------------------
8503
// - UpdateKeyRoutingTable() [Internal]
8504
// - GetRoutingIdFromOwnerId() [Internal]
8505
// - GetShortcutRoutingData() [Internal]
8506
// - CalcRoutingScore() [Internal]
8507
// - SetShortcutRouting() [Internal]
8508
// - TestShortcutRouting() [Internal]
8509
//-----------------------------------------------------------------------------
8510
// - IsKeyDown()
8511
// - IsKeyPressed()
8512
// - IsKeyReleased()
8513
//-----------------------------------------------------------------------------
8514
// - IsMouseDown()
8515
// - IsMouseClicked()
8516
// - IsMouseReleased()
8517
// - IsMouseDoubleClicked()
8518
// - GetMouseClickedCount()
8519
// - IsMouseHoveringRect() [Internal]
8520
// - IsMouseDragPastThreshold() [Internal]
8521
// - IsMouseDragging()
8522
// - GetMousePos()
8523
// - SetMousePos() [Internal]
8524
// - GetMousePosOnOpeningCurrentPopup()
8525
// - IsMousePosValid()
8526
// - IsAnyMouseDown()
8527
// - GetMouseDragDelta()
8528
// - ResetMouseDragDelta()
8529
// - GetMouseCursor()
8530
// - SetMouseCursor()
8531
//-----------------------------------------------------------------------------
8532
// - UpdateAliasKey()
8533
// - GetMergedModsFromKeys()
8534
// - UpdateKeyboardInputs()
8535
// - UpdateMouseInputs()
8536
//-----------------------------------------------------------------------------
8537
// - LockWheelingWindow [Internal]
8538
// - FindBestWheelingWindow [Internal]
8539
// - UpdateMouseWheel() [Internal]
8540
//-----------------------------------------------------------------------------
8541
// - SetNextFrameWantCaptureKeyboard()
8542
// - SetNextFrameWantCaptureMouse()
8543
//-----------------------------------------------------------------------------
8544
// - GetInputSourceName() [Internal]
8545
// - DebugPrintInputEvent() [Internal]
8546
// - UpdateInputEvents() [Internal]
8547
//-----------------------------------------------------------------------------
8548
// - GetKeyOwner() [Internal]
8549
// - TestKeyOwner() [Internal]
8550
// - SetKeyOwner() [Internal]
8551
// - SetItemKeyOwner() [Internal]
8552
// - Shortcut() [Internal]
8553
//-----------------------------------------------------------------------------
8554
8555
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8556
2.11M
{
8557
2.11M
    ImGuiContext& g = *ctx;
8558
8559
    // Special storage location for mods
8560
2.11M
    if (key & ImGuiMod_Mask_)
8561
487k
        key = ConvertSingleModFlagToKey(ctx, key);
8562
8563
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8564
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8565
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8566
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8567
#else
8568
2.11M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8569
2.11M
#endif
8570
2.11M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8571
2.11M
}
8572
8573
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8574
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8575
{
8576
    ImGuiContext& g = *GImGui;
8577
    IM_ASSERT(IsNamedKey(key));
8578
    const ImGuiKeyData* key_data = GetKeyData(key);
8579
    return (ImGuiKey)(key_data - g.IO.KeysData);
8580
}
8581
#endif
8582
8583
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8584
static const char* const GKeyNames[] =
8585
{
8586
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8587
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8588
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8589
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8590
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8591
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8592
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8593
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8594
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8595
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8596
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8597
    "GamepadStart", "GamepadBack",
8598
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8599
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8600
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8601
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8602
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8603
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8604
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8605
};
8606
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8607
8608
const char* ImGui::GetKeyName(ImGuiKey key)
8609
0
{
8610
0
    ImGuiContext& g = *GImGui;
8611
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8612
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8613
#else
8614
    if (IsLegacyKey(key))
8615
    {
8616
        if (g.IO.KeyMap[key] == -1)
8617
            return "N/A";
8618
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8619
        key = (ImGuiKey)g.IO.KeyMap[key];
8620
    }
8621
#endif
8622
0
    if (key == ImGuiKey_None)
8623
0
        return "None";
8624
0
    if (key & ImGuiMod_Mask_)
8625
0
        key = ConvertSingleModFlagToKey(&g, key);
8626
0
    if (!IsNamedKey(key))
8627
0
        return "Unknown";
8628
8629
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8630
0
}
8631
8632
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8633
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8634
0
{
8635
0
    ImGuiContext& g = *GImGui;
8636
0
    if (key_chord & ImGuiMod_Shortcut)
8637
0
        key_chord = ConvertShortcutMod(key_chord);
8638
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8639
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8640
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8641
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8642
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8643
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8644
0
}
8645
8646
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8647
// t1 = current time (e.g.: g.Time)
8648
// An event is triggered at:
8649
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8650
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8651
23.5k
{
8652
23.5k
    if (t1 == 0.0f)
8653
0
        return 1;
8654
23.5k
    if (t0 >= t1)
8655
0
        return 0;
8656
23.5k
    if (repeat_rate <= 0.0f)
8657
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8658
23.5k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8659
23.5k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8660
23.5k
    const int count = count_t1 - count_t0;
8661
23.5k
    return count;
8662
23.5k
}
8663
8664
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8665
41.7k
{
8666
41.7k
    ImGuiContext& g = *GImGui;
8667
41.7k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8668
41.7k
    {
8669
5.83k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8670
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8671
35.8k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8672
41.7k
    }
8673
41.7k
}
8674
8675
// Return value representing the number of presses in the last time period, for the given repeat rate
8676
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8677
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8678
23.5k
{
8679
23.5k
    ImGuiContext& g = *GImGui;
8680
23.5k
    const ImGuiKeyData* key_data = GetKeyData(key);
8681
23.5k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8682
0
        return 0;
8683
23.5k
    const float t = key_data->DownDuration;
8684
23.5k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8685
23.5k
}
8686
8687
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8688
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8689
0
{
8690
0
    return ImVec2(
8691
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8692
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8693
0
}
8694
8695
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8696
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8697
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8698
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8699
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8700
54.1k
{
8701
54.1k
    ImGuiContext& g = *GImGui;
8702
54.1k
    rt->EntriesNext.resize(0);
8703
7.63M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8704
7.57M
    {
8705
7.57M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8706
7.57M
        ImGuiKeyRoutingData* routing_entry;
8707
7.57M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8708
0
        {
8709
0
            routing_entry = &rt->Entries[old_routing_idx];
8710
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8711
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8712
0
            routing_entry->RoutingNextScore = 255;
8713
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8714
0
                continue;
8715
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8716
8717
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8718
0
            if (routing_entry->Mods == g.IO.KeyMods)
8719
0
            {
8720
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8721
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8722
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8723
0
            }
8724
0
        }
8725
8726
        // Rewrite linked-list
8727
7.57M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8728
7.57M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8729
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8730
7.57M
    }
8731
54.1k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8732
54.1k
}
8733
8734
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8735
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8736
0
{
8737
0
    ImGuiContext& g = *GImGui;
8738
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8739
0
}
8740
8741
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8742
0
{
8743
    // Majority of shortcuts will be Key + any number of Mods
8744
    // We accept _Single_ mod with ImGuiKey_None.
8745
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8746
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8747
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8748
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8749
0
    ImGuiContext& g = *GImGui;
8750
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8751
0
    ImGuiKeyRoutingData* routing_data;
8752
0
    if (key_chord & ImGuiMod_Shortcut)
8753
0
        key_chord = ConvertShortcutMod(key_chord);
8754
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8755
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8756
0
    if (key == ImGuiKey_None)
8757
0
        key = ConvertSingleModFlagToKey(&g, mods);
8758
0
    IM_ASSERT(IsNamedKey(key));
8759
8760
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8761
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8762
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8763
0
    {
8764
0
        routing_data = &rt->Entries[idx];
8765
0
        if (routing_data->Mods == mods)
8766
0
            return routing_data;
8767
0
    }
8768
8769
    // Add to linked-list
8770
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8771
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8772
0
    routing_data = &rt->Entries[routing_data_idx];
8773
0
    routing_data->Mods = (ImU16)mods;
8774
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8775
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8776
0
    return routing_data;
8777
0
}
8778
8779
// Current score encoding (lower is highest priority):
8780
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8781
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8782
//  -   2: ImGuiInputFlags_RouteGlobal
8783
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8784
//  - 254: ImGuiInputFlags_RouteGlobalLow
8785
//  - 255: never route
8786
// 'flags' should include an explicit routing policy
8787
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8788
0
{
8789
0
    if (flags & ImGuiInputFlags_RouteFocused)
8790
0
    {
8791
0
        ImGuiContext& g = *GImGui;
8792
0
        ImGuiWindow* focused = g.NavWindow;
8793
8794
        // ActiveID gets top priority
8795
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8796
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8797
0
            return 1;
8798
8799
        // Score based on distance to focused window (lower is better)
8800
        // Assuming both windows are submitting a routing request,
8801
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8802
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8803
        // Assuming only WindowA is submitting a routing request,
8804
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8805
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8806
0
            for (int next_score = 3; focused != NULL; next_score++)
8807
0
            {
8808
0
                if (focused == location)
8809
0
                {
8810
0
                    IM_ASSERT(next_score < 255);
8811
0
                    return next_score;
8812
0
                }
8813
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8814
0
            }
8815
0
        return 255;
8816
0
    }
8817
8818
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8819
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8820
0
        return 2;
8821
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8822
0
        return 254;
8823
0
    return 0;
8824
0
}
8825
8826
// Request a desired route for an input chord (key + mods).
8827
// Return true if the route is available this frame.
8828
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8829
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8830
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8831
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8832
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8833
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8834
108k
{
8835
108k
    ImGuiContext& g = *GImGui;
8836
108k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8837
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8838
108k
    else
8839
108k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8840
8841
108k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8842
0
        if (g.NavWindow == NULL)
8843
0
            return false;
8844
108k
    if (flags & ImGuiInputFlags_RouteAlways)
8845
108k
        return true;
8846
8847
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8848
0
    if (score == 255)
8849
0
        return false;
8850
8851
    // Submit routing for NEXT frame (assuming score is sufficient)
8852
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8853
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8854
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8855
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8856
0
    if (score < routing_data->RoutingNextScore)
8857
0
    {
8858
0
        routing_data->RoutingNext = routing_id;
8859
0
        routing_data->RoutingNextScore = (ImU8)score;
8860
0
    }
8861
8862
    // Return routing state for CURRENT frame
8863
0
    return routing_data->RoutingCurr == routing_id;
8864
0
}
8865
8866
// Currently unused by core (but used by tests)
8867
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8868
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8869
0
{
8870
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8871
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8872
0
    return routing_data->RoutingCurr == routing_id;
8873
0
}
8874
8875
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8876
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8877
bool ImGui::IsKeyDown(ImGuiKey key)
8878
818k
{
8879
818k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8880
818k
}
8881
8882
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8883
889k
{
8884
889k
    const ImGuiKeyData* key_data = GetKeyData(key);
8885
889k
    if (!key_data->Down)
8886
868k
        return false;
8887
21.6k
    if (!TestKeyOwner(key, owner_id))
8888
0
        return false;
8889
21.6k
    return true;
8890
21.6k
}
8891
8892
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8893
437k
{
8894
437k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8895
437k
}
8896
8897
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8898
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8899
813k
{
8900
813k
    const ImGuiKeyData* key_data = GetKeyData(key);
8901
813k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8902
765k
        return false;
8903
48.6k
    const float t = key_data->DownDuration;
8904
48.6k
    if (t < 0.0f)
8905
0
        return false;
8906
48.6k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8907
8908
48.6k
    bool pressed = (t == 0.0f);
8909
48.6k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8910
41.7k
    {
8911
41.7k
        float repeat_delay, repeat_rate;
8912
41.7k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8913
41.7k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8914
41.7k
    }
8915
48.6k
    if (!pressed)
8916
38.3k
        return false;
8917
10.2k
    if (!TestKeyOwner(key, owner_id))
8918
0
        return false;
8919
10.2k
    return true;
8920
10.2k
}
8921
8922
bool ImGui::IsKeyReleased(ImGuiKey key)
8923
0
{
8924
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8925
0
}
8926
8927
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8928
0
{
8929
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8930
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8931
0
        return false;
8932
0
    if (!TestKeyOwner(key, owner_id))
8933
0
        return false;
8934
0
    return true;
8935
0
}
8936
8937
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8938
0
{
8939
0
    ImGuiContext& g = *GImGui;
8940
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8941
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8942
0
}
8943
8944
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8945
8
{
8946
8
    ImGuiContext& g = *GImGui;
8947
8
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8948
8
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8949
8
}
8950
8951
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8952
1
{
8953
1
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8954
1
}
8955
8956
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8957
92
{
8958
92
    ImGuiContext& g = *GImGui;
8959
92
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8960
92
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8961
84
        return false;
8962
8
    const float t = g.IO.MouseDownDuration[button];
8963
8
    if (t < 0.0f)
8964
0
        return false;
8965
8
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8966
8967
8
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8968
8
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8969
8
    if (!pressed)
8970
2
        return false;
8971
8972
6
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8973
0
        return false;
8974
8975
6
    return true;
8976
6
}
8977
8978
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8979
0
{
8980
0
    ImGuiContext& g = *GImGui;
8981
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8982
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8983
0
}
8984
8985
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8986
91
{
8987
91
    ImGuiContext& g = *GImGui;
8988
91
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8989
91
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8990
91
}
8991
8992
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8993
1
{
8994
1
    ImGuiContext& g = *GImGui;
8995
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8996
1
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8997
1
}
8998
8999
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9000
0
{
9001
0
    ImGuiContext& g = *GImGui;
9002
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9003
0
    return g.IO.MouseClickedCount[button];
9004
0
}
9005
9006
// Test if mouse cursor is hovering given rectangle
9007
// NB- Rectangle is clipped by our current clip setting
9008
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9009
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9010
430k
{
9011
430k
    ImGuiContext& g = *GImGui;
9012
9013
    // Clip
9014
430k
    ImRect rect_clipped(r_min, r_max);
9015
430k
    if (clip)
9016
271k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9017
9018
    // Hit testing, expanded for touch input
9019
430k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9020
420k
        return false;
9021
10.3k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9022
0
        return false;
9023
10.3k
    return true;
9024
10.3k
}
9025
9026
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9027
// [Internal] This doesn't test if the button is pressed
9028
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9029
38
{
9030
38
    ImGuiContext& g = *GImGui;
9031
38
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9032
38
    if (lock_threshold < 0.0f)
9033
38
        lock_threshold = g.IO.MouseDragThreshold;
9034
38
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9035
38
}
9036
9037
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9038
39
{
9039
39
    ImGuiContext& g = *GImGui;
9040
39
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9041
39
    if (!g.IO.MouseDown[button])
9042
1
        return false;
9043
38
    return IsMouseDragPastThreshold(button, lock_threshold);
9044
39
}
9045
9046
ImVec2 ImGui::GetMousePos()
9047
15.1k
{
9048
15.1k
    ImGuiContext& g = *GImGui;
9049
15.1k
    return g.IO.MousePos;
9050
15.1k
}
9051
9052
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9053
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9054
void ImGui::TeleportMousePos(const ImVec2& pos)
9055
0
{
9056
0
    ImGuiContext& g = *GImGui;
9057
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9058
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9059
0
    g.IO.WantSetMousePos = true;
9060
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9061
0
}
9062
9063
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9064
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9065
0
{
9066
0
    ImGuiContext& g = *GImGui;
9067
0
    if (g.BeginPopupStack.Size > 0)
9068
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9069
0
    return g.IO.MousePos;
9070
0
}
9071
9072
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9073
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9074
188k
{
9075
    // The assert is only to silence a false-positive in XCode Static Analysis.
9076
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9077
188k
    IM_ASSERT(GImGui != NULL);
9078
188k
    const float MOUSE_INVALID = -256000.0f;
9079
188k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9080
188k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9081
188k
}
9082
9083
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9084
bool ImGui::IsAnyMouseDown()
9085
0
{
9086
0
    ImGuiContext& g = *GImGui;
9087
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9088
0
        if (g.IO.MouseDown[n])
9089
0
            return true;
9090
0
    return false;
9091
0
}
9092
9093
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9094
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9095
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9096
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9097
0
{
9098
0
    ImGuiContext& g = *GImGui;
9099
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9100
0
    if (lock_threshold < 0.0f)
9101
0
        lock_threshold = g.IO.MouseDragThreshold;
9102
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9103
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9104
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9105
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9106
0
    return ImVec2(0.0f, 0.0f);
9107
0
}
9108
9109
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9110
0
{
9111
0
    ImGuiContext& g = *GImGui;
9112
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9113
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9114
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9115
0
}
9116
9117
// Get desired mouse cursor shape.
9118
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9119
// updated during the frame, and locked in EndFrame()/Render().
9120
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9121
ImGuiMouseCursor ImGui::GetMouseCursor()
9122
0
{
9123
0
    ImGuiContext& g = *GImGui;
9124
0
    return g.MouseCursor;
9125
0
}
9126
9127
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9128
0
{
9129
0
    ImGuiContext& g = *GImGui;
9130
0
    g.MouseCursor = cursor_type;
9131
0
}
9132
9133
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9134
378k
{
9135
378k
    IM_ASSERT(ImGui::IsAliasKey(key));
9136
378k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9137
378k
    key_data->Down = v;
9138
378k
    key_data->AnalogValue = analog_value;
9139
378k
}
9140
9141
// [Internal] Do not use directly
9142
static ImGuiKeyChord GetMergedModsFromKeys()
9143
108k
{
9144
108k
    ImGuiKeyChord mods = 0;
9145
108k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9146
108k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9147
108k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9148
108k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9149
108k
    return mods;
9150
108k
}
9151
9152
static void ImGui::UpdateKeyboardInputs()
9153
54.1k
{
9154
54.1k
    ImGuiContext& g = *GImGui;
9155
54.1k
    ImGuiIO& io = g.IO;
9156
9157
    // Import legacy keys or verify they are not used
9158
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9159
    if (io.BackendUsingLegacyKeyArrays == 0)
9160
    {
9161
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9162
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9163
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9164
    }
9165
    else
9166
    {
9167
        if (g.FrameCount == 0)
9168
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9169
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9170
9171
        // Build reverse KeyMap (Named -> Legacy)
9172
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9173
            if (io.KeyMap[n] != -1)
9174
            {
9175
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9176
                io.KeyMap[io.KeyMap[n]] = n;
9177
            }
9178
9179
        // Import legacy keys into new ones
9180
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9181
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9182
            {
9183
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9184
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9185
                io.KeysData[key].Down = io.KeysDown[n];
9186
                if (key != n)
9187
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9188
                io.BackendUsingLegacyKeyArrays = 1;
9189
            }
9190
        if (io.BackendUsingLegacyKeyArrays == 1)
9191
        {
9192
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9193
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9194
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9195
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9196
        }
9197
    }
9198
9199
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9200
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9201
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9202
    {
9203
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9204
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9205
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9206
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9207
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9208
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9209
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9210
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9211
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9212
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9213
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9214
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9215
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9216
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9217
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9218
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9219
        #undef NAV_MAP_KEY
9220
    }
9221
#endif
9222
#endif
9223
9224
    // Update aliases
9225
324k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9226
270k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9227
54.1k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9228
54.1k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9229
9230
    // Synchronize io.KeyMods and io.KeyXXX values.
9231
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9232
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9233
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9234
54.1k
    io.KeyMods = GetMergedModsFromKeys();
9235
54.1k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9236
54.1k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9237
54.1k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9238
54.1k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9239
9240
    // Clear gamepad data if disabled
9241
54.1k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9242
1.35M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9243
1.29M
        {
9244
1.29M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9245
1.29M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9246
1.29M
        }
9247
9248
    // Update keys
9249
7.63M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9250
7.57M
    {
9251
7.57M
        ImGuiKeyData* key_data = &io.KeysData[i];
9252
7.57M
        key_data->DownDurationPrev = key_data->DownDuration;
9253
7.57M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9254
7.57M
    }
9255
9256
    // Update keys/input owner (named keys only): one entry per key
9257
7.63M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9258
7.57M
    {
9259
7.57M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9260
7.57M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9261
7.57M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9262
7.57M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9263
7.52M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9264
7.57M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9265
7.57M
    }
9266
9267
54.1k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9268
54.1k
}
9269
9270
static void ImGui::UpdateMouseInputs()
9271
54.1k
{
9272
54.1k
    ImGuiContext& g = *GImGui;
9273
54.1k
    ImGuiIO& io = g.IO;
9274
9275
    // Mouse Wheel swapping flag
9276
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9277
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9278
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9279
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9280
54.1k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9281
9282
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9283
54.1k
    if (IsMousePosValid(&io.MousePos))
9284
16.0k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9285
9286
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9287
54.1k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9288
14.7k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9289
39.3k
    else
9290
39.3k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9291
9292
    // Update stationary timer.
9293
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9294
54.1k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9295
54.1k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9296
54.1k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9297
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9298
9299
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9300
54.1k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9301
1.37k
        g.NavDisableMouseHover = false;
9302
9303
324k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9304
270k
    {
9305
270k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9306
270k
        io.MouseClickedCount[i] = 0; // Will be filled below
9307
270k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9308
270k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9309
270k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9310
270k
        if (io.MouseClicked[i])
9311
2.76k
        {
9312
2.76k
            bool is_repeated_click = false;
9313
2.76k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9314
1.70k
            {
9315
1.70k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9316
1.70k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9317
1.58k
                    is_repeated_click = true;
9318
1.70k
            }
9319
2.76k
            if (is_repeated_click)
9320
1.58k
                io.MouseClickedLastCount[i]++;
9321
1.18k
            else
9322
1.18k
                io.MouseClickedLastCount[i] = 1;
9323
2.76k
            io.MouseClickedTime[i] = g.Time;
9324
2.76k
            io.MouseClickedPos[i] = io.MousePos;
9325
2.76k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9326
2.76k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9327
2.76k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9328
2.76k
        }
9329
267k
        else if (io.MouseDown[i])
9330
11.1k
        {
9331
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9332
11.1k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9333
11.1k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9334
11.1k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9335
11.1k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9336
11.1k
        }
9337
9338
        // We provide io.MouseDoubleClicked[] as a legacy service
9339
270k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9340
9341
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9342
270k
        if (io.MouseClicked[i])
9343
2.76k
            g.NavDisableMouseHover = false;
9344
270k
    }
9345
54.1k
}
9346
9347
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9348
5
{
9349
5
    ImGuiContext& g = *GImGui;
9350
5
    if (window)
9351
3
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9352
2
    else
9353
2
        g.WheelingWindowReleaseTimer = 0.0f;
9354
5
    if (g.WheelingWindow == window)
9355
1
        return;
9356
4
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9357
4
    g.WheelingWindow = window;
9358
4
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9359
4
    if (window == NULL)
9360
2
    {
9361
2
        g.WheelingWindowStartFrame = -1;
9362
2
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9363
2
    }
9364
4
}
9365
9366
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9367
19
{
9368
    // For each axis, find window in the hierarchy that may want to use scrolling
9369
19
    ImGuiContext& g = *GImGui;
9370
19
    ImGuiWindow* windows[2] = { NULL, NULL };
9371
57
    for (int axis = 0; axis < 2; axis++)
9372
38
        if (wheel[axis] != 0.0f)
9373
24
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9374
0
            {
9375
                // Bubble up into parent window if:
9376
                // - a child window doesn't allow any scrolling.
9377
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9378
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9379
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9380
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9381
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9382
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9383
0
                    break; // select this window
9384
0
            }
9385
19
    if (windows[0] == NULL && windows[1] == NULL)
9386
0
        return NULL;
9387
9388
    // If there's only one window or only one axis then there's no ambiguity
9389
19
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9390
19
        return windows[1] ? windows[1] : windows[0];
9391
9392
    // If candidate are different windows we need to decide which one to prioritize
9393
    // - First frame: only find a winner if one axis is zero.
9394
    // - Subsequent frames: only find a winner when one is more than the other.
9395
0
    if (g.WheelingWindowStartFrame == -1)
9396
0
        g.WheelingWindowStartFrame = g.FrameCount;
9397
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9398
0
    {
9399
0
        g.WheelingWindowWheelRemainder = wheel;
9400
0
        return NULL;
9401
0
    }
9402
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9403
0
}
9404
9405
// Called by NewFrame()
9406
void ImGui::UpdateMouseWheel()
9407
54.1k
{
9408
    // Reset the locked window if we move the mouse or after the timer elapses.
9409
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9410
54.1k
    ImGuiContext& g = *GImGui;
9411
54.1k
    if (g.WheelingWindow != NULL)
9412
68
    {
9413
68
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9414
68
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9415
2
            g.WheelingWindowReleaseTimer = 0.0f;
9416
68
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9417
2
            LockWheelingWindow(NULL, 0.0f);
9418
68
    }
9419
9420
54.1k
    ImVec2 wheel;
9421
54.1k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9422
54.1k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9423
9424
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9425
54.1k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9426
54.1k
    if (!mouse_window || mouse_window->Collapsed)
9427
53.0k
        return;
9428
9429
    // Zoom / Scale window
9430
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9431
1.07k
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9432
0
    {
9433
0
        LockWheelingWindow(mouse_window, wheel.y);
9434
0
        ImGuiWindow* window = mouse_window;
9435
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9436
0
        const float scale = new_font_scale / window->FontWindowScale;
9437
0
        window->FontWindowScale = new_font_scale;
9438
0
        if (window == window->RootWindow)
9439
0
        {
9440
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9441
0
            SetWindowPos(window, window->Pos + offset, 0);
9442
0
            window->Size = ImTrunc(window->Size * scale);
9443
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9444
0
        }
9445
0
        return;
9446
0
    }
9447
1.07k
    if (g.IO.KeyCtrl)
9448
0
        return;
9449
9450
    // Mouse wheel scrolling
9451
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9452
1.07k
    if (g.IO.MouseWheelRequestAxisSwap)
9453
0
        wheel = ImVec2(wheel.y, 0.0f);
9454
9455
    // Maintain a rough average of moving magnitude on both axises
9456
    // FIXME: should by based on wall clock time rather than frame-counter
9457
1.07k
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9458
1.07k
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9459
9460
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9461
1.07k
    wheel += g.WheelingWindowWheelRemainder;
9462
1.07k
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9463
1.07k
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9464
1.05k
        return;
9465
9466
    // Mouse wheel scrolling: find target and apply
9467
    // - don't renew lock if axis doesn't apply on the window.
9468
    // - select a main axis when both axises are being moved.
9469
20
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9470
20
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9471
20
        {
9472
20
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9473
20
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9474
1
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9475
20
            if (do_scroll[ImGuiAxis_X])
9476
0
            {
9477
0
                LockWheelingWindow(window, wheel.x);
9478
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9479
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9480
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9481
0
            }
9482
20
            if (do_scroll[ImGuiAxis_Y])
9483
3
            {
9484
3
                LockWheelingWindow(window, wheel.y);
9485
3
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9486
3
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9487
3
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9488
3
            }
9489
20
        }
9490
20
}
9491
9492
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9493
0
{
9494
0
    ImGuiContext& g = *GImGui;
9495
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9496
0
}
9497
9498
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9499
0
{
9500
0
    ImGuiContext& g = *GImGui;
9501
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9502
0
}
9503
9504
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9505
static const char* GetInputSourceName(ImGuiInputSource source)
9506
0
{
9507
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9508
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9509
0
    return input_source_names[source];
9510
0
}
9511
static const char* GetMouseSourceName(ImGuiMouseSource source)
9512
0
{
9513
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9514
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9515
0
    return mouse_source_names[source];
9516
0
}
9517
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9518
0
{
9519
0
    ImGuiContext& g = *GImGui;
9520
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9521
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9522
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9523
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9524
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9525
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9526
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9527
0
}
9528
#endif
9529
9530
// Process input queue
9531
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9532
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9533
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9534
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9535
54.1k
{
9536
54.1k
    ImGuiContext& g = *GImGui;
9537
54.1k
    ImGuiIO& io = g.IO;
9538
9539
    // Only trickle chars<>key when working with InputText()
9540
    // FIXME: InputText() could parse event trail?
9541
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9542
54.1k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9543
9544
54.1k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9545
54.1k
    int  mouse_button_changed = 0x00;
9546
54.1k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9547
9548
54.1k
    int event_n = 0;
9549
68.7k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9550
18.5k
    {
9551
18.5k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9552
18.5k
        if (e->Type == ImGuiInputEventType_MousePos)
9553
3.64k
        {
9554
3.64k
            if (g.IO.WantSetMousePos)
9555
0
                continue;
9556
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9557
3.64k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9558
3.64k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9559
431
                break;
9560
3.21k
            io.MousePos = event_pos;
9561
3.21k
            io.MouseSource = e->MousePos.MouseSource;
9562
3.21k
            mouse_moved = true;
9563
3.21k
        }
9564
14.8k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9565
5.80k
        {
9566
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9567
5.80k
            const ImGuiMouseButton button = e->MouseButton.Button;
9568
5.80k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9569
5.80k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9570
1.74k
                break;
9571
4.06k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9572
0
                break;
9573
4.06k
            io.MouseDown[button] = e->MouseButton.Down;
9574
4.06k
            io.MouseSource = e->MouseButton.MouseSource;
9575
4.06k
            mouse_button_changed |= (1 << button);
9576
4.06k
        }
9577
9.05k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9578
1.71k
        {
9579
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9580
1.71k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9581
328
                break;
9582
1.39k
            io.MouseWheelH += e->MouseWheel.WheelX;
9583
1.39k
            io.MouseWheel += e->MouseWheel.WheelY;
9584
1.39k
            io.MouseSource = e->MouseWheel.MouseSource;
9585
1.39k
            mouse_wheeled = true;
9586
1.39k
        }
9587
7.33k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9588
0
        {
9589
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9590
0
        }
9591
7.33k
        else if (e->Type == ImGuiInputEventType_Key)
9592
2.94k
        {
9593
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9594
2.94k
            ImGuiKey key = e->Key.Key;
9595
2.94k
            IM_ASSERT(key != ImGuiKey_None);
9596
2.94k
            ImGuiKeyData* key_data = GetKeyData(key);
9597
2.94k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9598
2.94k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9599
621
                break;
9600
2.32k
            key_data->Down = e->Key.Down;
9601
2.32k
            key_data->AnalogValue = e->Key.AnalogValue;
9602
2.32k
            key_changed = true;
9603
2.32k
            key_changed_mask.SetBit(key_data_index);
9604
9605
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9606
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9607
            io.KeysDown[key_data_index] = key_data->Down;
9608
            if (io.KeyMap[key_data_index] != -1)
9609
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9610
#endif
9611
2.32k
        }
9612
4.38k
        else if (e->Type == ImGuiInputEventType_Text)
9613
4.00k
        {
9614
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9615
4.00k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9616
723
                break;
9617
3.27k
            unsigned int c = e->Text.Char;
9618
3.27k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9619
3.27k
            if (trickle_interleaved_keys_and_text)
9620
0
                text_inputted = true;
9621
3.27k
        }
9622
389
        else if (e->Type == ImGuiInputEventType_Focus)
9623
389
        {
9624
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9625
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9626
389
            const bool focus_lost = !e->AppFocused.Focused;
9627
389
            io.AppFocusLost = focus_lost;
9628
389
        }
9629
0
        else
9630
0
        {
9631
0
            IM_ASSERT(0 && "Unknown event!");
9632
0
        }
9633
18.5k
    }
9634
9635
    // Record trail (for domain-specific applications wanting to access a precise trail)
9636
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9637
68.7k
    for (int n = 0; n < event_n; n++)
9638
14.6k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9639
9640
    // [DEBUG]
9641
54.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9642
54.1k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9643
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9644
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9645
54.1k
#endif
9646
9647
    // Remaining events will be processed on the next frame
9648
54.1k
    if (event_n == g.InputEventsQueue.Size)
9649
50.2k
        g.InputEventsQueue.resize(0);
9650
3.84k
    else
9651
3.84k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9652
9653
    // Clear buttons state when focus is lost
9654
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9655
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9656
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9657
54.1k
    if (g.IO.AppFocusLost)
9658
389
        g.IO.ClearInputKeys();
9659
54.1k
}
9660
9661
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9662
0
{
9663
0
    if (!IsNamedKeyOrModKey(key))
9664
0
        return ImGuiKeyOwner_None;
9665
9666
0
    ImGuiContext& g = *GImGui;
9667
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9668
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9669
9670
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9671
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9672
0
            return ImGuiKeyOwner_None;
9673
9674
0
    return owner_id;
9675
0
}
9676
9677
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9678
// TestKeyOwner(..., None) : (owner == None)
9679
// TestKeyOwner(..., Any)  : no owner test
9680
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9681
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9682
140k
{
9683
140k
    if (!IsNamedKeyOrModKey(key))
9684
0
        return true;
9685
9686
140k
    ImGuiContext& g = *GImGui;
9687
140k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9688
60
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9689
0
            return false;
9690
9691
140k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9692
140k
    if (owner_id == ImGuiKeyOwner_Any)
9693
17.8k
        return (owner_data->LockThisFrame == false);
9694
9695
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9696
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9697
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9698
122k
    if (owner_data->OwnerCurr != owner_id)
9699
5
    {
9700
5
        if (owner_data->LockThisFrame)
9701
0
            return false;
9702
5
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9703
0
            return false;
9704
5
    }
9705
9706
122k
    return true;
9707
122k
}
9708
9709
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9710
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9711
// - SetKeyOwner(..., None)              : clears owner
9712
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9713
// - SetKeyOwner(..., Any or None, Lock) : set lock
9714
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9715
6
{
9716
6
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9717
6
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9718
9719
6
    ImGuiContext& g = *GImGui;
9720
6
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9721
6
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9722
9723
    // We cannot lock by default as it would likely break lots of legacy code.
9724
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9725
6
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9726
6
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9727
6
}
9728
9729
// Rarely used helper
9730
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9731
0
{
9732
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9733
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9734
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9735
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9736
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9737
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9738
0
}
9739
9740
// This is more or less equivalent to:
9741
//   if (IsItemHovered() || IsItemActive())
9742
//       SetKeyOwner(key, GetItemID());
9743
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9744
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9745
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9746
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9747
0
{
9748
0
    ImGuiContext& g = *GImGui;
9749
0
    ImGuiID id = g.LastItemData.ID;
9750
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9751
0
        return;
9752
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9753
0
        flags |= ImGuiInputFlags_CondDefault_;
9754
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9755
0
    {
9756
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9757
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9758
0
    }
9759
0
}
9760
9761
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9762
108k
{
9763
108k
    ImGuiContext& g = *GImGui;
9764
9765
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9766
108k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9767
108k
        flags |= ImGuiInputFlags_RouteFocused;
9768
108k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9769
0
        return false;
9770
9771
108k
    if (key_chord & ImGuiMod_Shortcut)
9772
0
        key_chord = ConvertShortcutMod(key_chord);
9773
108k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9774
108k
    if (g.IO.KeyMods != mods)
9775
108k
        return false;
9776
9777
    // Special storage location for mods
9778
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9779
0
    if (key == ImGuiKey_None)
9780
0
        key = ConvertSingleModFlagToKey(&g, mods);
9781
9782
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9783
0
        return false;
9784
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9785
9786
0
    return true;
9787
0
}
9788
9789
9790
//-----------------------------------------------------------------------------
9791
// [SECTION] ERROR CHECKING
9792
//-----------------------------------------------------------------------------
9793
9794
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9795
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9796
// If this triggers you have an issue:
9797
// - Most commonly: mismatched headers and compiled code version.
9798
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9799
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9800
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9801
//   Otherwise it is possible that different compilation units would see different structure layout
9802
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9803
1
{
9804
1
    bool error = false;
9805
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9806
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9807
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9808
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9809
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9810
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9811
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9812
1
    return !error;
9813
1
}
9814
9815
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9816
// This is causing issues and ambiguity and we need to retire that.
9817
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9818
// [Scenario 1]
9819
//  Previously this would make the window content size ~200x200:
9820
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9821
//  Instead, please submit an item:
9822
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9823
//  Alternative:
9824
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9825
// [Scenario 2]
9826
//  For reference this is one of the issue what we aim to fix with this change:
9827
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9828
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9829
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9830
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9831
0
{
9832
0
    ImGuiContext& g = *GImGui;
9833
0
    ImGuiWindow* window = g.CurrentWindow;
9834
0
    IM_ASSERT(window->DC.IsSetPos);
9835
0
    window->DC.IsSetPos = false;
9836
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9837
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9838
0
        return;
9839
0
    if (window->SkipItems)
9840
0
        return;
9841
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9842
#else
9843
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9844
#endif
9845
0
}
9846
9847
static void ImGui::ErrorCheckNewFrameSanityChecks()
9848
54.1k
{
9849
54.1k
    ImGuiContext& g = *GImGui;
9850
9851
    // Check user IM_ASSERT macro
9852
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9853
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9854
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9855
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9856
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9857
54.1k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9858
9859
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9860
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9861
#ifdef __EMSCRIPTEN__
9862
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9863
        g.IO.DeltaTime = 0.00001f;
9864
#endif
9865
9866
    // Check user data
9867
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9868
54.1k
    IM_ASSERT(g.Initialized);
9869
54.1k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9870
54.1k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9871
54.1k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9872
54.1k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9873
54.1k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9874
54.1k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9875
54.1k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9876
54.1k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9877
54.1k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9878
54.1k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9879
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9880
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9881
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9882
9883
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9884
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9885
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9886
#endif
9887
9888
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9889
54.1k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9890
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9891
9892
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9893
54.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9894
54.1k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9895
54.1k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9896
54.1k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9897
9898
    // Perform simple checks: multi-viewport and platform windows support
9899
54.1k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9900
1
    {
9901
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9902
0
        {
9903
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9904
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9905
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9906
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9907
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9908
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9909
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9910
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9911
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9912
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9913
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9914
0
        }
9915
1
        else
9916
1
        {
9917
            // Disable feature, our backends do not support it
9918
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9919
1
        }
9920
9921
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9922
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
9923
0
        {
9924
0
            IM_UNUSED(mon);
9925
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9926
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9927
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9928
0
        }
9929
1
    }
9930
54.1k
}
9931
9932
static void ImGui::ErrorCheckEndFrameSanityChecks()
9933
54.1k
{
9934
54.1k
    ImGuiContext& g = *GImGui;
9935
9936
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9937
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9938
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9939
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9940
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9941
    // while still correctly asserting on mid-frame key press events.
9942
54.1k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9943
54.1k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9944
54.1k
    IM_UNUSED(key_mods);
9945
9946
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9947
    //ErrorCheckEndFrameRecover();
9948
9949
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9950
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9951
54.1k
    if (g.CurrentWindowStack.Size != 1)
9952
0
    {
9953
0
        if (g.CurrentWindowStack.Size > 1)
9954
0
        {
9955
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
9956
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9957
0
            IM_UNUSED(window);
9958
0
            while (g.CurrentWindowStack.Size > 1)
9959
0
                End();
9960
0
        }
9961
0
        else
9962
0
        {
9963
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9964
0
        }
9965
0
    }
9966
9967
54.1k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9968
54.1k
}
9969
9970
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9971
// Must be called during or before EndFrame().
9972
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9973
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9974
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9975
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9976
0
{
9977
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9978
0
    ImGuiContext& g = *GImGui;
9979
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9980
0
    {
9981
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9982
0
        ImGuiWindow* window = g.CurrentWindow;
9983
0
        if (g.CurrentWindowStack.Size == 1)
9984
0
        {
9985
0
            IM_ASSERT(window->IsFallbackWindow);
9986
0
            break;
9987
0
        }
9988
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9989
0
        {
9990
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9991
0
            EndChild();
9992
0
        }
9993
0
        else
9994
0
        {
9995
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9996
0
            End();
9997
0
        }
9998
0
    }
9999
0
}
10000
10001
// Must be called before End()/EndChild()
10002
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10003
0
{
10004
0
    ImGuiContext& g = *GImGui;
10005
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10006
0
    {
10007
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10008
0
        EndTable();
10009
0
    }
10010
10011
0
    ImGuiWindow* window = g.CurrentWindow;
10012
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10013
0
    IM_ASSERT(window != NULL);
10014
0
    while (g.CurrentTabBar != NULL) //-V1044
10015
0
    {
10016
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10017
0
        EndTabBar();
10018
0
    }
10019
0
    while (window->DC.TreeDepth > 0)
10020
0
    {
10021
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10022
0
        TreePop();
10023
0
    }
10024
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10025
0
    {
10026
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10027
0
        EndGroup();
10028
0
    }
10029
0
    while (window->IDStack.Size > 1)
10030
0
    {
10031
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10032
0
        PopID();
10033
0
    }
10034
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10035
0
    {
10036
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10037
0
        EndDisabled();
10038
0
    }
10039
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10040
0
    {
10041
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10042
0
        PopStyleColor();
10043
0
    }
10044
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10045
0
    {
10046
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10047
0
        PopItemFlag();
10048
0
    }
10049
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10050
0
    {
10051
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10052
0
        PopStyleVar();
10053
0
    }
10054
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10055
0
    {
10056
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10057
0
        PopFont();
10058
0
    }
10059
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10060
0
    {
10061
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10062
0
        PopFocusScope();
10063
0
    }
10064
0
}
10065
10066
// Save current stack sizes for later compare
10067
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10068
159k
{
10069
159k
    ImGuiContext& g = *ctx;
10070
159k
    ImGuiWindow* window = g.CurrentWindow;
10071
159k
    SizeOfIDStack = (short)window->IDStack.Size;
10072
159k
    SizeOfColorStack = (short)g.ColorStack.Size;
10073
159k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10074
159k
    SizeOfFontStack = (short)g.FontStack.Size;
10075
159k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10076
159k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10077
159k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10078
159k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10079
159k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10080
159k
}
10081
10082
// Compare to detect usage errors
10083
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10084
159k
{
10085
159k
    ImGuiContext& g = *ctx;
10086
159k
    ImGuiWindow* window = g.CurrentWindow;
10087
159k
    IM_UNUSED(window);
10088
10089
    // Window stacks
10090
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10091
159k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10092
10093
    // Global stacks
10094
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10095
159k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10096
159k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10097
159k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10098
159k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10099
159k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10100
159k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10101
159k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10102
159k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10103
159k
}
10104
10105
10106
//-----------------------------------------------------------------------------
10107
// [SECTION] LAYOUT
10108
//-----------------------------------------------------------------------------
10109
// - ItemSize()
10110
// - ItemAdd()
10111
// - SameLine()
10112
// - GetCursorScreenPos()
10113
// - SetCursorScreenPos()
10114
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10115
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10116
// - GetCursorStartPos()
10117
// - Indent()
10118
// - Unindent()
10119
// - SetNextItemWidth()
10120
// - PushItemWidth()
10121
// - PushMultiItemsWidths()
10122
// - PopItemWidth()
10123
// - CalcItemWidth()
10124
// - CalcItemSize()
10125
// - GetTextLineHeight()
10126
// - GetTextLineHeightWithSpacing()
10127
// - GetFrameHeight()
10128
// - GetFrameHeightWithSpacing()
10129
// - GetContentRegionMax()
10130
// - GetContentRegionMaxAbs() [Internal]
10131
// - GetContentRegionAvail(),
10132
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10133
// - BeginGroup()
10134
// - EndGroup()
10135
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10136
//-----------------------------------------------------------------------------
10137
10138
// Advance cursor given item size for layout.
10139
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10140
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10141
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10142
102k
{
10143
102k
    ImGuiContext& g = *GImGui;
10144
102k
    ImGuiWindow* window = g.CurrentWindow;
10145
102k
    if (window->SkipItems)
10146
0
        return;
10147
10148
    // We increase the height in this function to accommodate for baseline offset.
10149
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10150
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10151
102k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10152
10153
102k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10154
102k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10155
10156
    // Always align ourselves on pixel boundaries
10157
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10158
102k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10159
102k
    window->DC.CursorPosPrevLine.y = line_y1;
10160
102k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10161
102k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10162
102k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10163
102k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10164
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10165
10166
102k
    window->DC.PrevLineSize.y = line_height;
10167
102k
    window->DC.CurrLineSize.y = 0.0f;
10168
102k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10169
102k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10170
102k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10171
10172
    // Horizontal layout mode
10173
102k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10174
0
        SameLine();
10175
102k
}
10176
10177
// Declare item bounding box for clipping and interaction.
10178
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10179
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10180
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10181
316k
{
10182
316k
    ImGuiContext& g = *GImGui;
10183
316k
    ImGuiWindow* window = g.CurrentWindow;
10184
10185
    // Set item data
10186
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10187
316k
    g.LastItemData.ID = id;
10188
316k
    g.LastItemData.Rect = bb;
10189
316k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10190
316k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10191
316k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10192
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10193
10194
    // Directional navigation processing
10195
316k
    if (id != 0)
10196
262k
    {
10197
262k
        KeepAliveID(id);
10198
10199
        // Runs prior to clipping early-out
10200
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10201
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10202
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10203
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10204
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10205
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10206
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10207
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10208
262k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10209
156k
        {
10210
156k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10211
156k
            if (g.NavId == id || g.NavAnyRequest)
10212
14.6k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10213
3.68k
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10214
3.68k
                        NavProcessItem();
10215
156k
        }
10216
10217
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10218
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10219
        // READ THE FAQ: https://dearimgui.com/faq
10220
262k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10221
262k
    }
10222
316k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10223
316k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10224
10225
#ifdef IMGUI_ENABLE_TEST_ENGINE
10226
    if (id != 0)
10227
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10228
#endif
10229
10230
    // Clipping test
10231
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10232
    //const bool is_clipped = IsClippedEx(bb, id);
10233
    //if (is_clipped)
10234
    //    return false;
10235
316k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10236
316k
    if (!is_rect_visible)
10237
48.6k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10238
48.6k
            if (!g.LogEnabled)
10239
48.6k
                return false;
10240
10241
    // [DEBUG]
10242
267k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10243
267k
    if (id != 0 && id == g.DebugLocateId)
10244
0
        DebugLocateItemResolveWithLastItem();
10245
267k
#endif
10246
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10247
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10248
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10249
10250
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10251
267k
    if (is_rect_visible)
10252
267k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10253
267k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10254
2.45k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10255
267k
    return true;
10256
316k
}
10257
10258
// Gets back to previous line and continue with horizontal layout
10259
//      offset_from_start_x == 0 : follow right after previous item
10260
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10261
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10262
//      spacing_w >= 0           : enforce spacing amount
10263
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10264
0
{
10265
0
    ImGuiContext& g = *GImGui;
10266
0
    ImGuiWindow* window = g.CurrentWindow;
10267
0
    if (window->SkipItems)
10268
0
        return;
10269
10270
0
    if (offset_from_start_x != 0.0f)
10271
0
    {
10272
0
        if (spacing_w < 0.0f)
10273
0
            spacing_w = 0.0f;
10274
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10275
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10276
0
    }
10277
0
    else
10278
0
    {
10279
0
        if (spacing_w < 0.0f)
10280
0
            spacing_w = g.Style.ItemSpacing.x;
10281
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10282
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10283
0
    }
10284
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10285
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10286
0
    window->DC.IsSameLine = true;
10287
0
}
10288
10289
ImVec2 ImGui::GetCursorScreenPos()
10290
66.1k
{
10291
66.1k
    ImGuiWindow* window = GetCurrentWindowRead();
10292
66.1k
    return window->DC.CursorPos;
10293
66.1k
}
10294
10295
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10296
0
{
10297
0
    ImGuiWindow* window = GetCurrentWindow();
10298
0
    window->DC.CursorPos = pos;
10299
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10300
0
    window->DC.IsSetPos = true;
10301
0
}
10302
10303
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10304
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10305
ImVec2 ImGui::GetCursorPos()
10306
0
{
10307
0
    ImGuiWindow* window = GetCurrentWindowRead();
10308
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10309
0
}
10310
10311
float ImGui::GetCursorPosX()
10312
0
{
10313
0
    ImGuiWindow* window = GetCurrentWindowRead();
10314
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10315
0
}
10316
10317
float ImGui::GetCursorPosY()
10318
0
{
10319
0
    ImGuiWindow* window = GetCurrentWindowRead();
10320
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10321
0
}
10322
10323
void ImGui::SetCursorPos(const ImVec2& local_pos)
10324
0
{
10325
0
    ImGuiWindow* window = GetCurrentWindow();
10326
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10327
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10328
0
    window->DC.IsSetPos = true;
10329
0
}
10330
10331
void ImGui::SetCursorPosX(float x)
10332
0
{
10333
0
    ImGuiWindow* window = GetCurrentWindow();
10334
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10335
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10336
0
    window->DC.IsSetPos = true;
10337
0
}
10338
10339
void ImGui::SetCursorPosY(float y)
10340
0
{
10341
0
    ImGuiWindow* window = GetCurrentWindow();
10342
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10343
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10344
0
    window->DC.IsSetPos = true;
10345
0
}
10346
10347
ImVec2 ImGui::GetCursorStartPos()
10348
0
{
10349
0
    ImGuiWindow* window = GetCurrentWindowRead();
10350
0
    return window->DC.CursorStartPos - window->Pos;
10351
0
}
10352
10353
void ImGui::Indent(float indent_w)
10354
0
{
10355
0
    ImGuiContext& g = *GImGui;
10356
0
    ImGuiWindow* window = GetCurrentWindow();
10357
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10358
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10359
0
}
10360
10361
void ImGui::Unindent(float indent_w)
10362
0
{
10363
0
    ImGuiContext& g = *GImGui;
10364
0
    ImGuiWindow* window = GetCurrentWindow();
10365
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10366
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10367
0
}
10368
10369
// Affect large frame+labels widgets only.
10370
void ImGui::SetNextItemWidth(float item_width)
10371
0
{
10372
0
    ImGuiContext& g = *GImGui;
10373
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10374
0
    g.NextItemData.Width = item_width;
10375
0
}
10376
10377
// FIXME: Remove the == 0.0f behavior?
10378
void ImGui::PushItemWidth(float item_width)
10379
0
{
10380
0
    ImGuiContext& g = *GImGui;
10381
0
    ImGuiWindow* window = g.CurrentWindow;
10382
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10383
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10384
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10385
0
}
10386
10387
void ImGui::PushMultiItemsWidths(int components, float w_full)
10388
0
{
10389
0
    ImGuiContext& g = *GImGui;
10390
0
    ImGuiWindow* window = g.CurrentWindow;
10391
0
    const ImGuiStyle& style = g.Style;
10392
0
    const float w_item_one  = ImMax(1.0f, IM_TRUNC((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10393
0
    const float w_item_last = ImMax(1.0f, IM_TRUNC(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10394
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10395
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10396
0
    for (int i = 0; i < components - 2; i++)
10397
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10398
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10399
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10400
0
}
10401
10402
void ImGui::PopItemWidth()
10403
0
{
10404
0
    ImGuiWindow* window = GetCurrentWindow();
10405
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10406
0
    window->DC.ItemWidthStack.pop_back();
10407
0
}
10408
10409
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10410
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10411
float ImGui::CalcItemWidth()
10412
0
{
10413
0
    ImGuiContext& g = *GImGui;
10414
0
    ImGuiWindow* window = g.CurrentWindow;
10415
0
    float w;
10416
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10417
0
        w = g.NextItemData.Width;
10418
0
    else
10419
0
        w = window->DC.ItemWidth;
10420
0
    if (w < 0.0f)
10421
0
    {
10422
0
        float region_max_x = GetContentRegionMaxAbs().x;
10423
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10424
0
    }
10425
0
    w = IM_TRUNC(w);
10426
0
    return w;
10427
0
}
10428
10429
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10430
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10431
// Note that only CalcItemWidth() is publicly exposed.
10432
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10433
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10434
0
{
10435
0
    ImGuiContext& g = *GImGui;
10436
0
    ImGuiWindow* window = g.CurrentWindow;
10437
10438
0
    ImVec2 region_max;
10439
0
    if (size.x < 0.0f || size.y < 0.0f)
10440
0
        region_max = GetContentRegionMaxAbs();
10441
10442
0
    if (size.x == 0.0f)
10443
0
        size.x = default_w;
10444
0
    else if (size.x < 0.0f)
10445
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10446
10447
0
    if (size.y == 0.0f)
10448
0
        size.y = default_h;
10449
0
    else if (size.y < 0.0f)
10450
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10451
10452
0
    return size;
10453
0
}
10454
10455
float ImGui::GetTextLineHeight()
10456
0
{
10457
0
    ImGuiContext& g = *GImGui;
10458
0
    return g.FontSize;
10459
0
}
10460
10461
float ImGui::GetTextLineHeightWithSpacing()
10462
51.0k
{
10463
51.0k
    ImGuiContext& g = *GImGui;
10464
51.0k
    return g.FontSize + g.Style.ItemSpacing.y;
10465
51.0k
}
10466
10467
float ImGui::GetFrameHeight()
10468
30
{
10469
30
    ImGuiContext& g = *GImGui;
10470
30
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10471
30
}
10472
10473
float ImGui::GetFrameHeightWithSpacing()
10474
0
{
10475
0
    ImGuiContext& g = *GImGui;
10476
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10477
0
}
10478
10479
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10480
10481
// FIXME: This is in window space (not screen space!).
10482
ImVec2 ImGui::GetContentRegionMax()
10483
0
{
10484
0
    ImGuiContext& g = *GImGui;
10485
0
    ImGuiWindow* window = g.CurrentWindow;
10486
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10487
0
    return mx - window->Pos;
10488
0
}
10489
10490
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10491
ImVec2 ImGui::GetContentRegionMaxAbs()
10492
51.0k
{
10493
51.0k
    ImGuiContext& g = *GImGui;
10494
51.0k
    ImGuiWindow* window = g.CurrentWindow;
10495
51.0k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10496
51.0k
    return mx;
10497
51.0k
}
10498
10499
ImVec2 ImGui::GetContentRegionAvail()
10500
51.0k
{
10501
51.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
10502
51.0k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10503
51.0k
}
10504
10505
// In window space (not screen space!)
10506
ImVec2 ImGui::GetWindowContentRegionMin()
10507
0
{
10508
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10509
0
    return window->ContentRegionRect.Min - window->Pos;
10510
0
}
10511
10512
ImVec2 ImGui::GetWindowContentRegionMax()
10513
51.0k
{
10514
51.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
10515
51.0k
    return window->ContentRegionRect.Max - window->Pos;
10516
51.0k
}
10517
10518
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10519
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10520
// FIXME-OPT: Could we safely early out on ->SkipItems?
10521
void ImGui::BeginGroup()
10522
0
{
10523
0
    ImGuiContext& g = *GImGui;
10524
0
    ImGuiWindow* window = g.CurrentWindow;
10525
10526
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10527
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10528
0
    group_data.WindowID = window->ID;
10529
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10530
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10531
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10532
0
    group_data.BackupIndent = window->DC.Indent;
10533
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10534
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10535
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10536
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10537
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10538
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10539
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10540
0
    group_data.EmitItem = true;
10541
10542
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10543
0
    window->DC.Indent = window->DC.GroupOffset;
10544
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10545
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10546
0
    if (g.LogEnabled)
10547
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10548
0
}
10549
10550
void ImGui::EndGroup()
10551
0
{
10552
0
    ImGuiContext& g = *GImGui;
10553
0
    ImGuiWindow* window = g.CurrentWindow;
10554
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10555
10556
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10557
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10558
10559
0
    if (window->DC.IsSetPos)
10560
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10561
10562
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10563
10564
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10565
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10566
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10567
0
    window->DC.Indent = group_data.BackupIndent;
10568
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10569
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10570
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10571
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
10572
0
    if (g.LogEnabled)
10573
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10574
10575
0
    if (!group_data.EmitItem)
10576
0
    {
10577
0
        g.GroupStack.pop_back();
10578
0
        return;
10579
0
    }
10580
10581
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10582
0
    ItemSize(group_bb.GetSize());
10583
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10584
10585
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10586
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10587
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10588
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10589
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10590
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10591
0
    if (group_contains_curr_active_id)
10592
0
        g.LastItemData.ID = g.ActiveId;
10593
0
    else if (group_contains_prev_active_id)
10594
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10595
0
    g.LastItemData.Rect = group_bb;
10596
10597
    // Forward Hovered flag
10598
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10599
0
    if (group_contains_curr_hovered_id)
10600
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10601
10602
    // Forward Edited flag
10603
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10604
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10605
10606
    // Forward Deactivated flag
10607
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10608
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10609
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10610
10611
0
    g.GroupStack.pop_back();
10612
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10613
0
}
10614
10615
10616
//-----------------------------------------------------------------------------
10617
// [SECTION] SCROLLING
10618
//-----------------------------------------------------------------------------
10619
10620
// Helper to snap on edges when aiming at an item very close to the edge,
10621
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10622
// When we refactor the scrolling API this may be configurable with a flag?
10623
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10624
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10625
0
{
10626
0
    if (target <= snap_min + snap_threshold)
10627
0
        return ImLerp(snap_min, target, center_ratio);
10628
0
    if (target >= snap_max - snap_threshold)
10629
0
        return ImLerp(target, snap_max, center_ratio);
10630
0
    return target;
10631
0
}
10632
10633
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10634
159k
{
10635
159k
    ImVec2 scroll = window->Scroll;
10636
159k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10637
478k
    for (int axis = 0; axis < 2; axis++)
10638
319k
    {
10639
319k
        if (window->ScrollTarget[axis] < FLT_MAX)
10640
43.9k
        {
10641
43.9k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10642
43.9k
            float scroll_target = window->ScrollTarget[axis];
10643
43.9k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10644
0
            {
10645
0
                float snap_min = 0.0f;
10646
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10647
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10648
0
            }
10649
43.9k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10650
43.9k
        }
10651
319k
        scroll[axis] = IM_TRUNC(ImMax(scroll[axis], 0.0f));
10652
319k
        if (!window->Collapsed && !window->SkipItems)
10653
313k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10654
319k
    }
10655
159k
    return scroll;
10656
159k
}
10657
10658
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10659
0
{
10660
0
    ImGuiContext& g = *GImGui;
10661
0
    ImGuiWindow* window = g.CurrentWindow;
10662
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10663
0
}
10664
10665
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10666
0
{
10667
0
    ScrollToRectEx(window, item_rect, flags);
10668
0
}
10669
10670
// Scroll to keep newly navigated item fully into view
10671
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10672
379
{
10673
379
    ImGuiContext& g = *GImGui;
10674
379
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10675
379
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10676
379
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10677
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10678
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10679
10680
    // Check that only one behavior is selected per axis
10681
379
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10682
379
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10683
10684
    // Defaults
10685
379
    ImGuiScrollFlags in_flags = flags;
10686
379
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10687
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10688
379
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10689
292
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10690
10691
379
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10692
379
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10693
379
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10694
379
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10695
10696
379
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10697
0
    {
10698
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10699
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10700
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10701
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10702
0
    }
10703
379
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10704
0
    {
10705
0
        if (can_be_fully_visible_x)
10706
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10707
0
        else
10708
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10709
0
    }
10710
10711
379
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10712
0
    {
10713
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10714
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10715
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10716
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10717
0
    }
10718
379
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10719
0
    {
10720
0
        if (can_be_fully_visible_y)
10721
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10722
0
        else
10723
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10724
0
    }
10725
10726
379
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10727
379
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10728
10729
    // Also scroll parent window to keep us into view if necessary
10730
379
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10731
0
    {
10732
        // FIXME-SCROLL: May be an option?
10733
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10734
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10735
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10736
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10737
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10738
0
    }
10739
10740
379
    return delta_scroll;
10741
379
}
10742
10743
float ImGui::GetScrollX()
10744
73.7k
{
10745
73.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10746
73.7k
    return window->Scroll.x;
10747
73.7k
}
10748
10749
float ImGui::GetScrollY()
10750
73.7k
{
10751
73.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10752
73.7k
    return window->Scroll.y;
10753
73.7k
}
10754
10755
float ImGui::GetScrollMaxX()
10756
0
{
10757
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10758
0
    return window->ScrollMax.x;
10759
0
}
10760
10761
float ImGui::GetScrollMaxY()
10762
0
{
10763
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10764
0
    return window->ScrollMax.y;
10765
0
}
10766
10767
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10768
23.1k
{
10769
23.1k
    window->ScrollTarget.x = scroll_x;
10770
23.1k
    window->ScrollTargetCenterRatio.x = 0.0f;
10771
23.1k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10772
23.1k
}
10773
10774
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10775
21.7k
{
10776
21.7k
    window->ScrollTarget.y = scroll_y;
10777
21.7k
    window->ScrollTargetCenterRatio.y = 0.0f;
10778
21.7k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10779
21.7k
}
10780
10781
void ImGui::SetScrollX(float scroll_x)
10782
22.8k
{
10783
22.8k
    ImGuiContext& g = *GImGui;
10784
22.8k
    SetScrollX(g.CurrentWindow, scroll_x);
10785
22.8k
}
10786
10787
void ImGui::SetScrollY(float scroll_y)
10788
18.8k
{
10789
18.8k
    ImGuiContext& g = *GImGui;
10790
18.8k
    SetScrollY(g.CurrentWindow, scroll_y);
10791
18.8k
}
10792
10793
// Note that a local position will vary depending on initial scroll value,
10794
// This is a little bit confusing so bear with us:
10795
//  - local_pos = (absolution_pos - window->Pos)
10796
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10797
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10798
//  - They mostly exist because of legacy API.
10799
// Following the rules above, when trying to work with scrolling code, consider that:
10800
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10801
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10802
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10803
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10804
0
{
10805
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10806
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10807
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10808
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10809
0
}
10810
10811
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10812
0
{
10813
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10814
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10815
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10816
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10817
0
}
10818
10819
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10820
0
{
10821
0
    ImGuiContext& g = *GImGui;
10822
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10823
0
}
10824
10825
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10826
0
{
10827
0
    ImGuiContext& g = *GImGui;
10828
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10829
0
}
10830
10831
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10832
void ImGui::SetScrollHereX(float center_x_ratio)
10833
0
{
10834
0
    ImGuiContext& g = *GImGui;
10835
0
    ImGuiWindow* window = g.CurrentWindow;
10836
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10837
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10838
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10839
10840
    // Tweak: snap on edges when aiming at an item very close to the edge
10841
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10842
0
}
10843
10844
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10845
void ImGui::SetScrollHereY(float center_y_ratio)
10846
0
{
10847
0
    ImGuiContext& g = *GImGui;
10848
0
    ImGuiWindow* window = g.CurrentWindow;
10849
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10850
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10851
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10852
10853
    // Tweak: snap on edges when aiming at an item very close to the edge
10854
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10855
0
}
10856
10857
//-----------------------------------------------------------------------------
10858
// [SECTION] TOOLTIPS
10859
//-----------------------------------------------------------------------------
10860
10861
bool ImGui::BeginTooltip()
10862
0
{
10863
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10864
0
}
10865
10866
bool ImGui::BeginItemTooltip()
10867
0
{
10868
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10869
0
        return false;
10870
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10871
0
}
10872
10873
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10874
0
{
10875
0
    ImGuiContext& g = *GImGui;
10876
10877
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10878
0
    {
10879
        // Drag and Drop tooltips are positioning differently than other tooltips:
10880
        // - offset visibility to increase visibility around mouse.
10881
        // - never clamp within outer viewport boundary.
10882
        // We call SetNextWindowPos() to enforce position and disable clamping.
10883
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
10884
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10885
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
10886
0
        SetNextWindowPos(tooltip_pos);
10887
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10888
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10889
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
10890
0
    }
10891
10892
0
    char window_name[16];
10893
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10894
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
10895
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10896
0
            if (window->Active)
10897
0
            {
10898
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10899
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
10900
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10901
0
            }
10902
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10903
0
    Begin(window_name, NULL, flags | extra_window_flags);
10904
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
10905
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
10906
    //if (!ret)
10907
    //    End();
10908
    //return ret;
10909
0
    return true;
10910
0
}
10911
10912
void ImGui::EndTooltip()
10913
0
{
10914
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10915
0
    End();
10916
0
}
10917
10918
void ImGui::SetTooltip(const char* fmt, ...)
10919
0
{
10920
0
    va_list args;
10921
0
    va_start(args, fmt);
10922
0
    SetTooltipV(fmt, args);
10923
0
    va_end(args);
10924
0
}
10925
10926
void ImGui::SetTooltipV(const char* fmt, va_list args)
10927
0
{
10928
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
10929
0
        return;
10930
0
    TextV(fmt, args);
10931
0
    EndTooltip();
10932
0
}
10933
10934
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
10935
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
10936
void ImGui::SetItemTooltip(const char* fmt, ...)
10937
0
{
10938
0
    va_list args;
10939
0
    va_start(args, fmt);
10940
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10941
0
        SetTooltipV(fmt, args);
10942
0
    va_end(args);
10943
0
}
10944
10945
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
10946
0
{
10947
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10948
0
        SetTooltipV(fmt, args);
10949
0
}
10950
10951
10952
//-----------------------------------------------------------------------------
10953
// [SECTION] POPUPS
10954
//-----------------------------------------------------------------------------
10955
10956
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10957
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10958
0
{
10959
0
    ImGuiContext& g = *GImGui;
10960
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10961
0
    {
10962
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10963
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10964
0
        IM_ASSERT(id == 0);
10965
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10966
0
            return g.OpenPopupStack.Size > 0;
10967
0
        else
10968
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10969
0
    }
10970
0
    else
10971
0
    {
10972
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10973
0
        {
10974
            // Return true if the popup is open anywhere in the popup stack
10975
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
10976
0
                if (popup_data.PopupId == id)
10977
0
                    return true;
10978
0
            return false;
10979
0
        }
10980
0
        else
10981
0
        {
10982
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10983
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10984
0
        }
10985
0
    }
10986
0
}
10987
10988
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10989
0
{
10990
0
    ImGuiContext& g = *GImGui;
10991
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10992
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10993
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10994
0
    return IsPopupOpen(id, popup_flags);
10995
0
}
10996
10997
// Also see FindBlockingModal(NULL)
10998
ImGuiWindow* ImGui::GetTopMostPopupModal()
10999
162k
{
11000
162k
    ImGuiContext& g = *GImGui;
11001
162k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11002
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11003
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11004
0
                return popup;
11005
162k
    return NULL;
11006
162k
}
11007
11008
// See Demo->Stacked Modal to confirm what this is for.
11009
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11010
54.1k
{
11011
54.1k
    ImGuiContext& g = *GImGui;
11012
54.1k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11013
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11014
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11015
0
                return popup;
11016
54.1k
    return NULL;
11017
54.1k
}
11018
11019
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11020
0
{
11021
0
    ImGuiContext& g = *GImGui;
11022
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11023
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11024
0
    OpenPopupEx(id, popup_flags);
11025
0
}
11026
11027
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11028
0
{
11029
0
    OpenPopupEx(id, popup_flags);
11030
0
}
11031
11032
// Mark popup as open (toggle toward open state).
11033
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11034
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11035
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11036
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11037
0
{
11038
0
    ImGuiContext& g = *GImGui;
11039
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11040
0
    const int current_stack_size = g.BeginPopupStack.Size;
11041
11042
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11043
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11044
0
            return;
11045
11046
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11047
0
    popup_ref.PopupId = id;
11048
0
    popup_ref.Window = NULL;
11049
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
11050
0
    popup_ref.OpenFrameCount = g.FrameCount;
11051
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11052
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11053
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11054
11055
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11056
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11057
0
    {
11058
0
        g.OpenPopupStack.push_back(popup_ref);
11059
0
    }
11060
0
    else
11061
0
    {
11062
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
11063
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
11064
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
11065
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
11066
0
        {
11067
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11068
0
        }
11069
0
        else
11070
0
        {
11071
            // Close child popups if any, then flag popup for open/reopen
11072
0
            ClosePopupToLevel(current_stack_size, false);
11073
0
            g.OpenPopupStack.push_back(popup_ref);
11074
0
        }
11075
11076
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11077
        // This is equivalent to what ClosePopupToLevel() does.
11078
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11079
        //    FocusWindow(parent_window);
11080
0
    }
11081
0
}
11082
11083
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11084
// This function closes any popups that are over 'ref_window'.
11085
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11086
12.8k
{
11087
12.8k
    ImGuiContext& g = *GImGui;
11088
12.8k
    if (g.OpenPopupStack.Size == 0)
11089
12.8k
        return;
11090
11091
    // Don't close our own child popup windows.
11092
0
    int popup_count_to_keep = 0;
11093
0
    if (ref_window)
11094
0
    {
11095
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11096
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11097
0
        {
11098
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11099
0
            if (!popup.Window)
11100
0
                continue;
11101
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11102
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
11103
0
                continue;
11104
11105
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11106
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
11107
            //     Window -> Popup1 -> Popup2 -> Popup3
11108
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11109
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11110
0
            bool ref_window_is_descendent_of_popup = false;
11111
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11112
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11113
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11114
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11115
0
                    {
11116
0
                        ref_window_is_descendent_of_popup = true;
11117
0
                        break;
11118
0
                    }
11119
0
            if (!ref_window_is_descendent_of_popup)
11120
0
                break;
11121
0
        }
11122
0
    }
11123
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11124
0
    {
11125
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11126
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11127
0
    }
11128
0
}
11129
11130
void ImGui::ClosePopupsExceptModals()
11131
0
{
11132
0
    ImGuiContext& g = *GImGui;
11133
11134
0
    int popup_count_to_keep;
11135
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11136
0
    {
11137
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11138
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11139
0
            break;
11140
0
    }
11141
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11142
0
        ClosePopupToLevel(popup_count_to_keep, true);
11143
0
}
11144
11145
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11146
0
{
11147
0
    ImGuiContext& g = *GImGui;
11148
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
11149
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11150
11151
    // Trim open popup stack
11152
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
11153
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
11154
0
    g.OpenPopupStack.resize(remaining);
11155
11156
0
    if (restore_focus_to_window_under_popup)
11157
0
    {
11158
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
11159
0
        if (focus_window && !focus_window->WasActive && popup_window)
11160
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11161
0
        else
11162
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11163
0
    }
11164
0
}
11165
11166
// Close the popup we have begin-ed into.
11167
void ImGui::CloseCurrentPopup()
11168
0
{
11169
0
    ImGuiContext& g = *GImGui;
11170
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11171
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11172
0
        return;
11173
11174
    // Closing a menu closes its top-most parent popup (unless a modal)
11175
0
    while (popup_idx > 0)
11176
0
    {
11177
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11178
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11179
0
        bool close_parent = false;
11180
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11181
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11182
0
                close_parent = true;
11183
0
        if (!close_parent)
11184
0
            break;
11185
0
        popup_idx--;
11186
0
    }
11187
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11188
0
    ClosePopupToLevel(popup_idx, true);
11189
11190
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11191
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11192
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11193
0
    if (ImGuiWindow* window = g.NavWindow)
11194
0
        window->DC.NavHideHighlightOneFrame = true;
11195
0
}
11196
11197
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11198
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11199
0
{
11200
0
    ImGuiContext& g = *GImGui;
11201
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11202
0
    {
11203
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11204
0
        return false;
11205
0
    }
11206
11207
0
    char name[20];
11208
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11209
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11210
0
    else
11211
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11212
11213
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11214
0
    bool is_open = Begin(name, NULL, flags);
11215
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11216
0
        EndPopup();
11217
11218
0
    return is_open;
11219
0
}
11220
11221
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11222
0
{
11223
0
    ImGuiContext& g = *GImGui;
11224
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11225
0
    {
11226
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11227
0
        return false;
11228
0
    }
11229
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11230
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11231
0
    return BeginPopupEx(id, flags);
11232
0
}
11233
11234
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11235
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
11236
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11237
0
{
11238
0
    ImGuiContext& g = *GImGui;
11239
0
    ImGuiWindow* window = g.CurrentWindow;
11240
0
    const ImGuiID id = window->GetID(name);
11241
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11242
0
    {
11243
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11244
0
        return false;
11245
0
    }
11246
11247
    // Center modal windows by default for increased visibility
11248
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11249
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11250
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11251
0
    {
11252
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11253
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11254
0
    }
11255
11256
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11257
0
    const bool is_open = Begin(name, p_open, flags);
11258
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11259
0
    {
11260
0
        EndPopup();
11261
0
        if (is_open)
11262
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11263
0
        return false;
11264
0
    }
11265
0
    return is_open;
11266
0
}
11267
11268
void ImGui::EndPopup()
11269
0
{
11270
0
    ImGuiContext& g = *GImGui;
11271
0
    ImGuiWindow* window = g.CurrentWindow;
11272
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11273
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11274
11275
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11276
0
    if (g.NavWindow == window)
11277
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11278
11279
    // Child-popups don't need to be laid out
11280
0
    IM_ASSERT(g.WithinEndChild == false);
11281
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11282
0
        g.WithinEndChild = true;
11283
0
    End();
11284
0
    g.WithinEndChild = false;
11285
0
}
11286
11287
// Helper to open a popup if mouse button is released over the item
11288
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11289
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11290
0
{
11291
0
    ImGuiContext& g = *GImGui;
11292
0
    ImGuiWindow* window = g.CurrentWindow;
11293
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11294
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11295
0
    {
11296
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11297
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11298
0
        OpenPopupEx(id, popup_flags);
11299
0
    }
11300
0
}
11301
11302
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11303
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11304
// - To create a popup with a specific identifier, pass it in str_id.
11305
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11306
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11307
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11308
//   This is essentially the same as:
11309
//       id = str_id ? GetID(str_id) : GetItemID();
11310
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11311
//       return BeginPopup(id);
11312
//   Which is essentially the same as:
11313
//       id = str_id ? GetID(str_id) : GetItemID();
11314
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11315
//           OpenPopup(id);
11316
//       return BeginPopup(id);
11317
//   The main difference being that this is tweaked to avoid computing the ID twice.
11318
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11319
0
{
11320
0
    ImGuiContext& g = *GImGui;
11321
0
    ImGuiWindow* window = g.CurrentWindow;
11322
0
    if (window->SkipItems)
11323
0
        return false;
11324
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11325
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11326
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11327
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11328
0
        OpenPopupEx(id, popup_flags);
11329
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11330
0
}
11331
11332
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11333
0
{
11334
0
    ImGuiContext& g = *GImGui;
11335
0
    ImGuiWindow* window = g.CurrentWindow;
11336
0
    if (!str_id)
11337
0
        str_id = "window_context";
11338
0
    ImGuiID id = window->GetID(str_id);
11339
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11340
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11341
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11342
0
            OpenPopupEx(id, popup_flags);
11343
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11344
0
}
11345
11346
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11347
0
{
11348
0
    ImGuiContext& g = *GImGui;
11349
0
    ImGuiWindow* window = g.CurrentWindow;
11350
0
    if (!str_id)
11351
0
        str_id = "void_context";
11352
0
    ImGuiID id = window->GetID(str_id);
11353
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11354
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11355
0
        if (GetTopMostPopupModal() == NULL)
11356
0
            OpenPopupEx(id, popup_flags);
11357
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11358
0
}
11359
11360
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11361
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11362
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11363
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11364
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11365
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11366
0
{
11367
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11368
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11369
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11370
11371
    // Combo Box policy (we want a connecting edge)
11372
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11373
0
    {
11374
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11375
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11376
0
        {
11377
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11378
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11379
0
                continue;
11380
0
            ImVec2 pos;
11381
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11382
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11383
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11384
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11385
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11386
0
                continue;
11387
0
            *last_dir = dir;
11388
0
            return pos;
11389
0
        }
11390
0
    }
11391
11392
    // Tooltip and Default popup policy
11393
    // (Always first try the direction we used on the last frame, if any)
11394
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11395
0
    {
11396
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11397
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11398
0
        {
11399
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11400
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11401
0
                continue;
11402
11403
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11404
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11405
11406
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11407
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11408
0
                continue;
11409
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11410
0
                continue;
11411
11412
0
            ImVec2 pos;
11413
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11414
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11415
11416
            // Clamp top-left corner of popup
11417
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11418
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11419
11420
0
            *last_dir = dir;
11421
0
            return pos;
11422
0
        }
11423
0
    }
11424
11425
    // Fallback when not enough room:
11426
0
    *last_dir = ImGuiDir_None;
11427
11428
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11429
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11430
0
        return ref_pos + ImVec2(2, 2);
11431
11432
    // Otherwise try to keep within display
11433
0
    ImVec2 pos = ref_pos;
11434
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11435
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11436
0
    return pos;
11437
0
}
11438
11439
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11440
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11441
0
{
11442
0
    ImGuiContext& g = *GImGui;
11443
0
    ImRect r_screen;
11444
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11445
0
    {
11446
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11447
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11448
0
        r_screen.Min = monitor.WorkPos;
11449
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11450
0
    }
11451
0
    else
11452
0
    {
11453
        // Use the full viewport area (not work area) for popups
11454
0
        r_screen = window->Viewport->GetMainRect();
11455
0
    }
11456
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11457
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11458
0
    return r_screen;
11459
0
}
11460
11461
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11462
0
{
11463
0
    ImGuiContext& g = *GImGui;
11464
11465
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11466
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11467
0
    {
11468
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11469
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11470
0
        ImGuiWindow* parent_window = window->ParentWindow;
11471
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11472
0
        ImRect r_avoid;
11473
0
        if (parent_window->DC.MenuBarAppending)
11474
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11475
0
        else
11476
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11477
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11478
0
    }
11479
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11480
0
    {
11481
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11482
0
    }
11483
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11484
0
    {
11485
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11486
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11487
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11488
0
        IM_ASSERT(g.CurrentWindow == window);
11489
0
        const float scale = g.Style.MouseCursorScale;
11490
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11491
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11492
0
        ImRect r_avoid;
11493
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11494
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11495
0
        else
11496
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11497
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11498
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11499
0
    }
11500
0
    IM_ASSERT(0);
11501
0
    return window->Pos;
11502
0
}
11503
11504
//-----------------------------------------------------------------------------
11505
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11506
//-----------------------------------------------------------------------------
11507
11508
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11509
// In our terminology those should be interchangeable, yet right now this is super confusing.
11510
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11511
11512
void ImGui::SetNavWindow(ImGuiWindow* window)
11513
12.6k
{
11514
12.6k
    ImGuiContext& g = *GImGui;
11515
12.6k
    if (g.NavWindow != window)
11516
12.6k
    {
11517
12.6k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11518
12.6k
        g.NavWindow = window;
11519
12.6k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11520
12.6k
    }
11521
12.6k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11522
12.6k
    NavUpdateAnyRequestFlag();
11523
12.6k
}
11524
11525
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11526
4.86k
{
11527
4.86k
    ImGuiContext& g = *GImGui;
11528
4.86k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11529
4.86k
}
11530
11531
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11532
683
{
11533
683
    ImGuiContext& g = *GImGui;
11534
683
    IM_ASSERT(g.NavWindow != NULL);
11535
683
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11536
683
    g.NavId = id;
11537
683
    g.NavLayer = nav_layer;
11538
683
    g.NavFocusScopeId = focus_scope_id;
11539
683
    g.NavWindow->NavLastIds[nav_layer] = id;
11540
683
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11541
11542
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11543
683
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11544
683
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11545
683
}
11546
11547
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11548
6
{
11549
6
    ImGuiContext& g = *GImGui;
11550
6
    IM_ASSERT(id != 0);
11551
11552
6
    if (g.NavWindow != window)
11553
6
       SetNavWindow(window);
11554
11555
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11556
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11557
6
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11558
6
    g.NavId = id;
11559
6
    g.NavLayer = nav_layer;
11560
6
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11561
6
    window->NavLastIds[nav_layer] = id;
11562
6
    if (g.LastItemData.ID == id)
11563
6
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11564
11565
6
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11566
0
        g.NavDisableMouseHover = true;
11567
6
    else
11568
6
        g.NavDisableHighlight = true;
11569
11570
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11571
6
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11572
6
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11573
6
}
11574
11575
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11576
593
{
11577
593
    if (ImFabs(dx) > ImFabs(dy))
11578
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11579
593
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11580
593
}
11581
11582
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11583
1.18k
{
11584
1.18k
    if (cand_max < curr_min)
11585
352
        return cand_max - curr_min;
11586
834
    if (curr_max < cand_min)
11587
241
        return cand_min - curr_max;
11588
593
    return 0.0f;
11589
834
}
11590
11591
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11592
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11593
1.46k
{
11594
1.46k
    ImGuiContext& g = *GImGui;
11595
1.46k
    ImGuiWindow* window = g.CurrentWindow;
11596
1.46k
    if (g.NavLayer != window->DC.NavLayerCurrent)
11597
869
        return false;
11598
11599
    // FIXME: Those are not good variables names
11600
593
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11601
593
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11602
593
    g.NavScoringDebugCount++;
11603
11604
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11605
593
    if (window->ParentWindow == g.NavWindow)
11606
0
    {
11607
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11608
0
        if (!window->ClipRect.Overlaps(cand))
11609
0
            return false;
11610
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11611
0
    }
11612
11613
    // Compute distance between boxes
11614
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11615
593
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11616
593
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11617
593
    if (dby != 0.0f && dbx != 0.0f)
11618
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11619
593
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11620
11621
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11622
593
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11623
593
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11624
593
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11625
11626
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11627
593
    ImGuiDir quadrant;
11628
593
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11629
593
    if (dbx != 0.0f || dby != 0.0f)
11630
593
    {
11631
        // For non-overlapping boxes, use distance between boxes
11632
593
        dax = dbx;
11633
593
        day = dby;
11634
593
        dist_axial = dist_box;
11635
593
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11636
593
    }
11637
0
    else if (dcx != 0.0f || dcy != 0.0f)
11638
0
    {
11639
        // For overlapping boxes with different centers, use distance between centers
11640
0
        dax = dcx;
11641
0
        day = dcy;
11642
0
        dist_axial = dist_center;
11643
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11644
0
    }
11645
0
    else
11646
0
    {
11647
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11648
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11649
0
    }
11650
11651
593
    const ImGuiDir move_dir = g.NavMoveDir;
11652
#if IMGUI_DEBUG_NAV_SCORING
11653
    char buf[200];
11654
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11655
    {
11656
        if (quadrant == move_dir)
11657
        {
11658
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11659
            ImDrawList* draw_list = GetForegroundDrawList(window);
11660
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11661
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11662
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11663
        }
11664
    }
11665
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11666
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11667
    if (debug_hovering || debug_tty)
11668
    {
11669
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11670
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11671
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11672
        if (debug_hovering)
11673
        {
11674
            ImDrawList* draw_list = GetForegroundDrawList(window);
11675
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11676
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11677
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11678
            draw_list->AddText(cand.Max, ~0U, buf);
11679
        }
11680
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11681
    }
11682
#endif
11683
11684
    // Is it in the quadrant we're interested in moving to?
11685
593
    bool new_best = false;
11686
593
    if (quadrant == move_dir)
11687
593
    {
11688
        // Does it beat the current best candidate?
11689
593
        if (dist_box < result->DistBox)
11690
593
        {
11691
593
            result->DistBox = dist_box;
11692
593
            result->DistCenter = dist_center;
11693
593
            return true;
11694
593
        }
11695
0
        if (dist_box == result->DistBox)
11696
0
        {
11697
            // Try using distance between center points to break ties
11698
0
            if (dist_center < result->DistCenter)
11699
0
            {
11700
0
                result->DistCenter = dist_center;
11701
0
                new_best = true;
11702
0
            }
11703
0
            else if (dist_center == result->DistCenter)
11704
0
            {
11705
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11706
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11707
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11708
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11709
0
                    new_best = true;
11710
0
            }
11711
0
        }
11712
0
    }
11713
11714
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11715
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11716
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11717
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11718
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11719
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11720
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11721
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11722
0
            {
11723
0
                result->DistAxial = dist_axial;
11724
0
                new_best = true;
11725
0
            }
11726
11727
0
    return new_best;
11728
593
}
11729
11730
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11731
684
{
11732
684
    ImGuiContext& g = *GImGui;
11733
684
    ImGuiWindow* window = g.CurrentWindow;
11734
684
    result->Window = window;
11735
684
    result->ID = g.LastItemData.ID;
11736
684
    result->FocusScopeId = g.CurrentFocusScopeId;
11737
684
    result->InFlags = g.LastItemData.InFlags;
11738
684
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11739
684
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
11740
0
    {
11741
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11742
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11743
0
    }
11744
684
}
11745
11746
// True when current work location may be scrolled horizontally when moving left / right.
11747
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11748
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11749
264k
{
11750
264k
    ImGuiContext& g = *GImGui;
11751
264k
    ImGuiWindow* window = g.CurrentWindow;
11752
264k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11753
264k
}
11754
11755
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11756
// This is called after LastItemData is set, but NextItemData is also still valid.
11757
static void ImGui::NavProcessItem()
11758
3.68k
{
11759
3.68k
    ImGuiContext& g = *GImGui;
11760
3.68k
    ImGuiWindow* window = g.CurrentWindow;
11761
3.68k
    const ImGuiID id = g.LastItemData.ID;
11762
3.68k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11763
11764
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11765
3.68k
    if (window->DC.NavIsScrollPushableX == false)
11766
0
    {
11767
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11768
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11769
0
    }
11770
3.68k
    const ImRect nav_bb = g.LastItemData.NavRect;
11771
11772
    // Process Init Request
11773
3.68k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11774
1
    {
11775
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11776
1
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11777
1
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11778
1
        {
11779
1
            NavApplyItemToResult(&g.NavInitResult);
11780
1
        }
11781
1
        if (candidate_for_nav_default_focus)
11782
1
        {
11783
1
            g.NavInitRequest = false; // Found a match, clear request
11784
1
            NavUpdateAnyRequestFlag();
11785
1
        }
11786
1
    }
11787
11788
    // Process Move Request (scoring for navigation)
11789
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11790
3.68k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11791
1.32k
    {
11792
1.32k
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
11793
1.32k
        if (is_tabbing)
11794
180
        {
11795
180
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11796
180
        }
11797
1.14k
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11798
919
        {
11799
919
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11800
919
            if (NavScoreItem(result))
11801
327
                NavApplyItemToResult(result);
11802
11803
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11804
919
            const float VISIBLE_RATIO = 0.70f;
11805
919
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11806
543
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11807
543
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11808
266
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11809
919
        }
11810
1.32k
    }
11811
11812
    // Update information for currently focused/navigated item
11813
3.68k
    if (g.NavId == id)
11814
2.99k
    {
11815
2.99k
        if (g.NavWindow != window)
11816
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11817
2.99k
        g.NavLayer = window->DC.NavLayerCurrent;
11818
2.99k
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11819
2.99k
        g.NavIdIsAlive = true;
11820
2.99k
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
11821
0
        {
11822
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11823
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11824
0
        }
11825
2.99k
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11826
2.99k
    }
11827
3.68k
}
11828
11829
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11830
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11831
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11832
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11833
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11834
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11835
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11836
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11837
180
{
11838
180
    ImGuiContext& g = *GImGui;
11839
11840
180
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11841
180
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11842
90
            return;
11843
11844
    // - Can always land on an item when using API call.
11845
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11846
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11847
90
    bool can_stop;
11848
90
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11849
0
        can_stop = true;
11850
90
    else
11851
90
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11852
11853
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11854
90
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11855
90
    if (g.NavTabbingDir == +1)
11856
90
    {
11857
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11858
90
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11859
90
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11860
90
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11861
0
            NavMoveRequestResolveWithLastItem(result);
11862
90
        else if (g.NavId == id)
11863
90
            g.NavTabbingCounter = 1;
11864
90
    }
11865
0
    else if (g.NavTabbingDir == -1)
11866
0
    {
11867
        // Tab Backward
11868
0
        if (g.NavId == id)
11869
0
        {
11870
0
            if (result->ID)
11871
0
            {
11872
0
                g.NavMoveScoringItems = false;
11873
0
                NavUpdateAnyRequestFlag();
11874
0
            }
11875
0
        }
11876
0
        else if (can_stop)
11877
0
        {
11878
            // Keep applying until reaching NavId
11879
0
            NavApplyItemToResult(result);
11880
0
        }
11881
0
    }
11882
0
    else if (g.NavTabbingDir == 0)
11883
0
    {
11884
0
        if (can_stop && g.NavId == id)
11885
0
            NavMoveRequestResolveWithLastItem(result);
11886
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
11887
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11888
0
    }
11889
90
}
11890
11891
bool ImGui::NavMoveRequestButNoResultYet()
11892
43.4k
{
11893
43.4k
    ImGuiContext& g = *GImGui;
11894
43.4k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11895
43.4k
}
11896
11897
// FIXME: ScoringRect is not set
11898
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11899
4.12k
{
11900
4.12k
    ImGuiContext& g = *GImGui;
11901
4.12k
    IM_ASSERT(g.NavWindow != NULL);
11902
11903
4.12k
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
11904
2.14k
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11905
11906
4.12k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11907
4.12k
    g.NavMoveDir = move_dir;
11908
4.12k
    g.NavMoveDirForDebug = move_dir;
11909
4.12k
    g.NavMoveClipDir = clip_dir;
11910
4.12k
    g.NavMoveFlags = move_flags;
11911
4.12k
    g.NavMoveScrollFlags = scroll_flags;
11912
4.12k
    g.NavMoveForwardToNextFrame = false;
11913
4.12k
    g.NavMoveKeyMods = g.IO.KeyMods;
11914
4.12k
    g.NavMoveResultLocal.Clear();
11915
4.12k
    g.NavMoveResultLocalVisible.Clear();
11916
4.12k
    g.NavMoveResultOther.Clear();
11917
4.12k
    g.NavTabbingCounter = 0;
11918
4.12k
    g.NavTabbingResultFirst.Clear();
11919
4.12k
    NavUpdateAnyRequestFlag();
11920
4.12k
}
11921
11922
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11923
0
{
11924
0
    ImGuiContext& g = *GImGui;
11925
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11926
0
    NavApplyItemToResult(result);
11927
0
    NavUpdateAnyRequestFlag();
11928
0
}
11929
11930
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
11931
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
11932
0
{
11933
0
    ImGuiContext& g = *GImGui;
11934
0
    g.NavMoveScoringItems = false;
11935
0
    g.LastItemData.ID = tree_node_data->ID;
11936
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
11937
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
11938
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
11939
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11940
0
    NavUpdateAnyRequestFlag();
11941
0
}
11942
11943
void ImGui::NavMoveRequestCancel()
11944
40
{
11945
40
    ImGuiContext& g = *GImGui;
11946
40
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11947
40
    NavUpdateAnyRequestFlag();
11948
40
}
11949
11950
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11951
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11952
0
{
11953
0
    ImGuiContext& g = *GImGui;
11954
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11955
0
    NavMoveRequestCancel();
11956
0
    g.NavMoveForwardToNextFrame = true;
11957
0
    g.NavMoveDir = move_dir;
11958
0
    g.NavMoveClipDir = clip_dir;
11959
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11960
0
    g.NavMoveScrollFlags = scroll_flags;
11961
0
}
11962
11963
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11964
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11965
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11966
0
{
11967
0
    ImGuiContext& g = *GImGui;
11968
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11969
11970
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
11971
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
11972
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11973
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
11974
0
}
11975
11976
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11977
// This way we could find the last focused window among our children. It would be much less confusing this way?
11978
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11979
37.3k
{
11980
37.3k
    ImGuiWindow* parent = nav_window;
11981
71.9k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11982
34.5k
        parent = parent->ParentWindow;
11983
37.3k
    if (parent && parent != nav_window)
11984
34.5k
        parent->NavLastChildNavWindow = nav_window;
11985
37.3k
}
11986
11987
// Restore the last focused child.
11988
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11989
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11990
0
{
11991
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11992
0
        return window->NavLastChildNavWindow;
11993
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11994
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11995
0
            return tab->Window;
11996
0
    return window;
11997
0
}
11998
11999
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12000
0
{
12001
0
    ImGuiContext& g = *GImGui;
12002
0
    if (layer == ImGuiNavLayer_Main)
12003
0
    {
12004
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12005
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12006
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12007
0
        if (prev_nav_window)
12008
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12009
0
    }
12010
0
    ImGuiWindow* window = g.NavWindow;
12011
0
    if (window->NavLastIds[layer] != 0)
12012
0
    {
12013
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12014
0
    }
12015
0
    else
12016
0
    {
12017
0
        g.NavLayer = layer;
12018
0
        NavInitWindow(window, true);
12019
0
    }
12020
0
}
12021
12022
void ImGui::NavRestoreHighlightAfterMove()
12023
884
{
12024
884
    ImGuiContext& g = *GImGui;
12025
884
    g.NavDisableHighlight = false;
12026
884
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12027
884
}
12028
12029
static inline void ImGui::NavUpdateAnyRequestFlag()
12030
70.9k
{
12031
70.9k
    ImGuiContext& g = *GImGui;
12032
70.9k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12033
70.9k
    if (g.NavAnyRequest)
12034
70.9k
        IM_ASSERT(g.NavWindow != NULL);
12035
70.9k
}
12036
12037
// This needs to be called before we submit any widget (aka in or before Begin)
12038
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12039
13
{
12040
    // FIXME: ChildWindow test here is wrong for docking
12041
13
    ImGuiContext& g = *GImGui;
12042
13
    IM_ASSERT(window == g.NavWindow);
12043
12044
13
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12045
0
    {
12046
0
        g.NavId = 0;
12047
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12048
0
        return;
12049
0
    }
12050
12051
13
    bool init_for_nav = false;
12052
13
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12053
13
        init_for_nav = true;
12054
13
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12055
13
    if (init_for_nav)
12056
13
    {
12057
13
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12058
13
        g.NavInitRequest = true;
12059
13
        g.NavInitRequestFromMove = false;
12060
13
        g.NavInitResult.ID = 0;
12061
13
        NavUpdateAnyRequestFlag();
12062
13
    }
12063
0
    else
12064
0
    {
12065
0
        g.NavId = window->NavLastIds[0];
12066
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12067
0
    }
12068
13
}
12069
12070
static ImVec2 ImGui::NavCalcPreferredRefPos()
12071
0
{
12072
0
    ImGuiContext& g = *GImGui;
12073
0
    ImGuiWindow* window = g.NavWindow;
12074
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12075
0
    {
12076
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12077
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12078
        // In theory we could move that +1.0f offset in OpenPopupEx()
12079
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12080
0
        return ImVec2(p.x + 1.0f, p.y);
12081
0
    }
12082
0
    else
12083
0
    {
12084
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12085
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12086
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12087
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12088
0
        {
12089
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12090
0
            rect_rel.Translate(window->Scroll - next_scroll);
12091
0
        }
12092
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12093
0
        ImGuiViewport* viewport = window->Viewport;
12094
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12095
0
    }
12096
0
}
12097
12098
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12099
0
{
12100
0
    ImGuiContext& g = *GImGui;
12101
0
    float repeat_delay, repeat_rate;
12102
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12103
12104
0
    ImGuiKey key_less, key_more;
12105
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12106
0
    {
12107
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12108
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12109
0
    }
12110
0
    else
12111
0
    {
12112
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12113
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12114
0
    }
12115
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12116
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12117
0
        amount = 0.0f;
12118
0
    return amount;
12119
0
}
12120
12121
static void ImGui::NavUpdate()
12122
54.1k
{
12123
54.1k
    ImGuiContext& g = *GImGui;
12124
54.1k
    ImGuiIO& io = g.IO;
12125
12126
54.1k
    io.WantSetMousePos = false;
12127
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12128
12129
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12130
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12131
54.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12132
54.1k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12133
54.1k
    if (nav_gamepad_active)
12134
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12135
0
            if (IsKeyDown(key))
12136
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12137
54.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12138
54.1k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12139
54.1k
    if (nav_keyboard_active)
12140
54.1k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12141
378k
            if (IsKeyDown(key))
12142
13.3k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12143
12144
    // Process navigation init request (select first/default focus)
12145
54.1k
    g.NavJustMovedToId = 0;
12146
54.1k
    if (g.NavInitResult.ID != 0)
12147
1
        NavInitRequestApplyResult();
12148
54.1k
    g.NavInitRequest = false;
12149
54.1k
    g.NavInitRequestFromMove = false;
12150
54.1k
    g.NavInitResult.ID = 0;
12151
12152
    // Process navigation move request
12153
54.1k
    if (g.NavMoveSubmitted)
12154
3.86k
        NavMoveRequestApplyResult();
12155
54.1k
    g.NavTabbingCounter = 0;
12156
54.1k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12157
12158
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12159
54.1k
    bool set_mouse_pos = false;
12160
54.1k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12161
805
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12162
805
            set_mouse_pos = true;
12163
54.1k
    g.NavMousePosDirty = false;
12164
54.1k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12165
12166
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12167
54.1k
    if (g.NavWindow)
12168
37.3k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12169
54.1k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12170
257
        g.NavWindow->NavLastChildNavWindow = NULL;
12171
12172
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12173
54.1k
    NavUpdateWindowing();
12174
12175
    // Set output flags for user application
12176
54.1k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12177
54.1k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12178
12179
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12180
54.1k
    NavUpdateCancelRequest();
12181
12182
    // Process manual activation request
12183
54.1k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12184
54.1k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12185
54.1k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12186
3.10k
    {
12187
3.10k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
12188
3.10k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
12189
3.10k
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
12190
3.10k
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
12191
3.10k
        if (g.ActiveId == 0 && activate_pressed)
12192
10
        {
12193
10
            g.NavActivateId = g.NavId;
12194
10
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12195
10
        }
12196
3.10k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12197
2
        {
12198
2
            g.NavActivateId = g.NavId;
12199
2
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12200
2
        }
12201
3.10k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12202
140
            g.NavActivateDownId = g.NavId;
12203
3.10k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12204
12
            g.NavActivatePressedId = g.NavId;
12205
3.10k
    }
12206
54.1k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12207
0
        g.NavDisableHighlight = true;
12208
54.1k
    if (g.NavActivateId != 0)
12209
54.1k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12210
12211
    // Process programmatic activation request
12212
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12213
54.1k
    if (g.NavNextActivateId != 0)
12214
0
    {
12215
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12216
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12217
0
    }
12218
54.1k
    g.NavNextActivateId = 0;
12219
12220
    // Process move requests
12221
54.1k
    NavUpdateCreateMoveRequest();
12222
54.1k
    if (g.NavMoveDir == ImGuiDir_None)
12223
52.1k
        NavUpdateCreateTabbingRequest();
12224
54.1k
    NavUpdateAnyRequestFlag();
12225
54.1k
    g.NavIdIsAlive = false;
12226
12227
    // Scrolling
12228
54.1k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12229
37.3k
    {
12230
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12231
37.3k
        ImGuiWindow* window = g.NavWindow;
12232
37.3k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12233
37.3k
        const ImGuiDir move_dir = g.NavMoveDir;
12234
37.3k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12235
1.30k
        {
12236
1.30k
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12237
304
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12238
1.30k
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12239
1.00k
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12240
1.30k
        }
12241
12242
        // *Normal* Manual scroll with LStick
12243
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12244
37.3k
        if (nav_gamepad_active)
12245
0
        {
12246
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12247
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12248
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12249
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12250
0
            if (scroll_dir.y != 0.0f)
12251
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12252
0
        }
12253
37.3k
    }
12254
12255
    // Always prioritize mouse highlight if navigation is disabled
12256
54.1k
    if (!nav_keyboard_active && !nav_gamepad_active)
12257
0
    {
12258
0
        g.NavDisableHighlight = true;
12259
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12260
0
    }
12261
12262
    // Update mouse position if requested
12263
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12264
54.1k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12265
0
        TeleportMousePos(NavCalcPreferredRefPos());
12266
12267
    // [DEBUG]
12268
54.1k
    g.NavScoringDebugCount = 0;
12269
#if IMGUI_DEBUG_NAV_RECTS
12270
    if (ImGuiWindow* debug_window = g.NavWindow)
12271
    {
12272
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12273
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12274
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12275
    }
12276
#endif
12277
54.1k
}
12278
12279
void ImGui::NavInitRequestApplyResult()
12280
1
{
12281
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12282
1
    ImGuiContext& g = *GImGui;
12283
1
    if (!g.NavWindow)
12284
1
        return;
12285
12286
0
    ImGuiNavItemData* result = &g.NavInitResult;
12287
0
    if (g.NavId != result->ID)
12288
0
    {
12289
0
        g.NavJustMovedToId = result->ID;
12290
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12291
0
        g.NavJustMovedToKeyMods = 0;
12292
0
    }
12293
12294
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12295
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12296
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12297
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12298
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12299
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12300
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12301
0
    if (g.NavInitRequestFromMove)
12302
0
        NavRestoreHighlightAfterMove();
12303
0
}
12304
12305
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12306
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12307
1.98k
{
12308
    // Bias initial rect
12309
1.98k
    ImGuiContext& g = *GImGui;
12310
1.98k
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12311
12312
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12313
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12314
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12315
1.98k
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12316
1.98k
    {
12317
1.98k
        if (preferred_pos_rel.x == FLT_MAX)
12318
697
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12319
1.98k
        if (preferred_pos_rel.y == FLT_MAX)
12320
1.42k
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12321
1.98k
    }
12322
12323
    // Apply general bias on the other axis
12324
1.98k
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12325
1.62k
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12326
355
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12327
355
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12328
1.98k
}
12329
12330
void ImGui::NavUpdateCreateMoveRequest()
12331
54.1k
{
12332
54.1k
    ImGuiContext& g = *GImGui;
12333
54.1k
    ImGuiIO& io = g.IO;
12334
54.1k
    ImGuiWindow* window = g.NavWindow;
12335
54.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12336
54.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12337
12338
54.1k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12339
0
    {
12340
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12341
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12342
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12343
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12344
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12345
0
    }
12346
54.1k
    else
12347
54.1k
    {
12348
        // Initiate directional inputs request
12349
54.1k
        g.NavMoveDir = ImGuiDir_None;
12350
54.1k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12351
54.1k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12352
54.1k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12353
37.3k
        {
12354
37.3k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12355
37.3k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12356
37.3k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12357
37.3k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12358
37.3k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12359
37.3k
        }
12360
54.1k
        g.NavMoveClipDir = g.NavMoveDir;
12361
54.1k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12362
54.1k
    }
12363
12364
    // Update PageUp/PageDown/Home/End scroll
12365
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12366
54.1k
    float scoring_rect_offset_y = 0.0f;
12367
54.1k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12368
35.7k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12369
54.1k
    if (scoring_rect_offset_y != 0.0f)
12370
303
    {
12371
303
        g.NavScoringNoClipRect = window->InnerRect;
12372
303
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12373
303
    }
12374
12375
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12376
#if IMGUI_DEBUG_NAV_SCORING
12377
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12378
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12379
    if (io.KeyCtrl)
12380
    {
12381
        if (g.NavMoveDir == ImGuiDir_None)
12382
            g.NavMoveDir = g.NavMoveDirForDebug;
12383
        g.NavMoveClipDir = g.NavMoveDir;
12384
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12385
    }
12386
#endif
12387
12388
    // Submit
12389
54.1k
    g.NavMoveForwardToNextFrame = false;
12390
54.1k
    if (g.NavMoveDir != ImGuiDir_None)
12391
1.98k
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12392
12393
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12394
54.1k
    if (g.NavMoveSubmitted && g.NavId == 0)
12395
1.38k
    {
12396
1.38k
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12397
1.38k
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12398
1.38k
        g.NavInitResult.ID = 0;
12399
1.38k
        g.NavDisableHighlight = false;
12400
1.38k
    }
12401
12402
    // When using gamepad, we project the reference nav bounding box into window visible area.
12403
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12404
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12405
54.1k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12406
0
    {
12407
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12408
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12409
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12410
12411
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12412
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12413
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12414
12415
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12416
0
        {
12417
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12418
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12419
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12420
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12421
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12422
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12423
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12424
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12425
0
            g.NavId = 0;
12426
0
        }
12427
0
    }
12428
12429
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12430
54.1k
    ImRect scoring_rect;
12431
54.1k
    if (window != NULL)
12432
37.3k
    {
12433
37.3k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12434
37.3k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12435
37.3k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12436
37.3k
        if (g.NavMoveSubmitted)
12437
1.98k
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12438
37.3k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12439
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12440
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12441
37.3k
    }
12442
54.1k
    g.NavScoringRect = scoring_rect;
12443
54.1k
    g.NavScoringNoClipRect.Add(scoring_rect);
12444
54.1k
}
12445
12446
void ImGui::NavUpdateCreateTabbingRequest()
12447
52.1k
{
12448
52.1k
    ImGuiContext& g = *GImGui;
12449
52.1k
    ImGuiWindow* window = g.NavWindow;
12450
52.1k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12451
52.1k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12452
16.7k
        return;
12453
12454
35.3k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12455
35.3k
    if (!tab_pressed)
12456
33.2k
        return;
12457
12458
    // Initiate tabbing request
12459
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12460
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12461
2.14k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12462
2.14k
    if (nav_keyboard_active)
12463
2.14k
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12464
0
    else
12465
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12466
2.14k
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12467
2.14k
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12468
2.14k
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12469
2.14k
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12470
2.14k
    g.NavTabbingCounter = -1;
12471
2.14k
}
12472
12473
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12474
void ImGui::NavMoveRequestApplyResult()
12475
3.86k
{
12476
3.86k
    ImGuiContext& g = *GImGui;
12477
#if IMGUI_DEBUG_NAV_SCORING
12478
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12479
        return;
12480
#endif
12481
12482
    // Select which result to use
12483
3.86k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12484
12485
    // Tabbing forward wrap
12486
3.86k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12487
2.04k
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12488
87
            result = &g.NavTabbingResultFirst;
12489
12490
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12491
3.86k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12492
3.86k
    if (result == NULL)
12493
3.48k
    {
12494
3.48k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12495
1.95k
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12496
3.48k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12497
214
            NavRestoreHighlightAfterMove();
12498
3.48k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12499
3.48k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12500
3.48k
        return;
12501
3.48k
    }
12502
12503
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12504
379
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12505
237
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12506
0
            result = &g.NavMoveResultLocalVisible;
12507
12508
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12509
379
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12510
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12511
0
            result = &g.NavMoveResultOther;
12512
379
    IM_ASSERT(g.NavWindow && result->Window);
12513
12514
    // Scroll to keep newly navigated item fully into view.
12515
379
    if (g.NavLayer == ImGuiNavLayer_Main)
12516
379
    {
12517
379
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12518
379
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12519
12520
379
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12521
55
        {
12522
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12523
55
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12524
55
            SetScrollY(result->Window, scroll_target);
12525
55
        }
12526
379
    }
12527
12528
379
    if (g.NavWindow != result->Window)
12529
0
    {
12530
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12531
0
        g.NavWindow = result->Window;
12532
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12533
0
    }
12534
379
    if (g.ActiveId != result->ID)
12535
379
        ClearActiveID();
12536
12537
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12538
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12539
379
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12540
237
    {
12541
237
        g.NavJustMovedToId = result->ID;
12542
237
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12543
237
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12544
237
    }
12545
12546
    // Apply new NavID/Focus
12547
379
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12548
379
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12549
379
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12550
379
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12551
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12552
12553
    // Restore last preferred position for current axis
12554
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12555
379
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
12556
292
    {
12557
292
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12558
292
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12559
292
    }
12560
12561
    // Tabbing: Activates Inputable, otherwise only Focus
12562
379
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12563
87
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12564
12565
    // Activate
12566
379
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12567
0
    {
12568
0
        g.NavNextActivateId = result->ID;
12569
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12570
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12571
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12572
0
    }
12573
12574
    // Enable nav highlight
12575
379
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12576
379
        NavRestoreHighlightAfterMove();
12577
379
}
12578
12579
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12580
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12581
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12582
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12583
static void ImGui::NavUpdateCancelRequest()
12584
54.1k
{
12585
54.1k
    ImGuiContext& g = *GImGui;
12586
54.1k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12587
54.1k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12588
54.1k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12589
53.7k
        return;
12590
12591
363
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12592
363
    if (g.ActiveId != 0)
12593
0
    {
12594
0
        ClearActiveID();
12595
0
    }
12596
363
    else if (g.NavLayer != ImGuiNavLayer_Main)
12597
0
    {
12598
        // Leave the "menu" layer
12599
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12600
0
        NavRestoreHighlightAfterMove();
12601
0
    }
12602
363
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12603
291
    {
12604
        // Exit child window
12605
291
        ImGuiWindow* child_window = g.NavWindow;
12606
291
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12607
291
        IM_ASSERT(child_window->ChildId != 0);
12608
291
        ImRect child_rect = child_window->Rect();
12609
291
        FocusWindow(parent_window);
12610
291
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12611
291
        NavRestoreHighlightAfterMove();
12612
291
    }
12613
72
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12614
0
    {
12615
        // Close open popup/menu
12616
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12617
0
    }
12618
72
    else
12619
72
    {
12620
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12621
72
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12622
3
            g.NavWindow->NavLastIds[0] = 0;
12623
72
        g.NavId = 0;
12624
72
    }
12625
363
}
12626
12627
// Handle PageUp/PageDown/Home/End keys
12628
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12629
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12630
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12631
static float ImGui::NavUpdatePageUpPageDown()
12632
35.7k
{
12633
35.7k
    ImGuiContext& g = *GImGui;
12634
35.7k
    ImGuiWindow* window = g.NavWindow;
12635
35.7k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12636
0
        return 0.0f;
12637
12638
35.7k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12639
35.7k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12640
35.7k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12641
35.7k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12642
35.7k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12643
27.2k
        return 0.0f;
12644
12645
8.51k
    if (g.NavLayer != ImGuiNavLayer_Main)
12646
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12647
12648
8.51k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12649
6.77k
    {
12650
        // Fallback manual-scroll when window has no navigable item
12651
6.77k
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12652
1.34k
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12653
5.42k
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12654
83
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12655
5.34k
        else if (home_pressed)
12656
74
            SetScrollY(window, 0.0f);
12657
5.26k
        else if (end_pressed)
12658
266
            SetScrollY(window, window->ScrollMax.y);
12659
6.77k
    }
12660
1.74k
    else
12661
1.74k
    {
12662
1.74k
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12663
1.74k
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12664
1.74k
        float nav_scoring_rect_offset_y = 0.0f;
12665
1.74k
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12666
157
        {
12667
157
            nav_scoring_rect_offset_y = -page_offset_y;
12668
157
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12669
157
            g.NavMoveClipDir = ImGuiDir_Up;
12670
157
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12671
157
        }
12672
1.58k
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12673
146
        {
12674
146
            nav_scoring_rect_offset_y = +page_offset_y;
12675
146
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12676
146
            g.NavMoveClipDir = ImGuiDir_Down;
12677
146
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12678
146
        }
12679
1.43k
        else if (home_pressed)
12680
2
        {
12681
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12682
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12683
            // Preserve current horizontal position if we have any.
12684
2
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12685
2
            if (nav_rect_rel.IsInverted())
12686
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12687
2
            g.NavMoveDir = ImGuiDir_Down;
12688
2
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12689
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12690
2
        }
12691
1.43k
        else if (end_pressed)
12692
60
        {
12693
60
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12694
60
            if (nav_rect_rel.IsInverted())
12695
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12696
60
            g.NavMoveDir = ImGuiDir_Up;
12697
60
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12698
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12699
60
        }
12700
1.74k
        return nav_scoring_rect_offset_y;
12701
1.74k
    }
12702
6.77k
    return 0.0f;
12703
8.51k
}
12704
12705
static void ImGui::NavEndFrame()
12706
54.1k
{
12707
54.1k
    ImGuiContext& g = *GImGui;
12708
12709
    // Show CTRL+TAB list window
12710
54.1k
    if (g.NavWindowingTarget != NULL)
12711
0
        NavUpdateWindowingOverlay();
12712
12713
    // Perform wrap-around in menus
12714
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12715
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12716
54.1k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12717
0
        NavUpdateCreateWrappingRequest();
12718
54.1k
}
12719
12720
static void ImGui::NavUpdateCreateWrappingRequest()
12721
0
{
12722
0
    ImGuiContext& g = *GImGui;
12723
0
    ImGuiWindow* window = g.NavWindow;
12724
12725
0
    bool do_forward = false;
12726
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12727
0
    ImGuiDir clip_dir = g.NavMoveDir;
12728
12729
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12730
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12731
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12732
0
    {
12733
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12734
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12735
0
        {
12736
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12737
0
            clip_dir = ImGuiDir_Up;
12738
0
        }
12739
0
        do_forward = true;
12740
0
    }
12741
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12742
0
    {
12743
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12744
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12745
0
        {
12746
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12747
0
            clip_dir = ImGuiDir_Down;
12748
0
        }
12749
0
        do_forward = true;
12750
0
    }
12751
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12752
0
    {
12753
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12754
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12755
0
        {
12756
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12757
0
            clip_dir = ImGuiDir_Left;
12758
0
        }
12759
0
        do_forward = true;
12760
0
    }
12761
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12762
0
    {
12763
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12764
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12765
0
        {
12766
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12767
0
            clip_dir = ImGuiDir_Right;
12768
0
        }
12769
0
        do_forward = true;
12770
0
    }
12771
0
    if (!do_forward)
12772
0
        return;
12773
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12774
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12775
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12776
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12777
0
}
12778
12779
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12780
0
{
12781
0
    ImGuiContext& g = *GImGui;
12782
0
    IM_UNUSED(g);
12783
0
    int order = window->FocusOrder;
12784
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12785
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12786
0
    return order;
12787
0
}
12788
12789
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12790
0
{
12791
0
    ImGuiContext& g = *GImGui;
12792
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12793
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12794
0
            return g.WindowsFocusOrder[i];
12795
0
    return NULL;
12796
0
}
12797
12798
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12799
0
{
12800
0
    ImGuiContext& g = *GImGui;
12801
0
    IM_ASSERT(g.NavWindowingTarget);
12802
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12803
0
        return;
12804
12805
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12806
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12807
0
    if (!window_target)
12808
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12809
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12810
0
    {
12811
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12812
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12813
0
    }
12814
0
    g.NavWindowingToggleLayer = false;
12815
0
}
12816
12817
// Windowing management mode
12818
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12819
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12820
static void ImGui::NavUpdateWindowing()
12821
54.1k
{
12822
54.1k
    ImGuiContext& g = *GImGui;
12823
54.1k
    ImGuiIO& io = g.IO;
12824
12825
54.1k
    ImGuiWindow* apply_focus_window = NULL;
12826
54.1k
    bool apply_toggle_layer = false;
12827
12828
54.1k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12829
54.1k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12830
54.1k
    if (!allow_windowing)
12831
0
        g.NavWindowingTarget = NULL;
12832
12833
    // Fade out
12834
54.1k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12835
0
    {
12836
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12837
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12838
0
            g.NavWindowingTargetAnim = NULL;
12839
0
    }
12840
12841
    // Start CTRL+Tab or Square+L/R window selection
12842
54.1k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12843
54.1k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12844
54.1k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12845
54.1k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12846
54.1k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12847
54.1k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12848
54.1k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12849
54.1k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12850
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12851
0
        {
12852
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12853
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12854
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12855
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12856
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12857
12858
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12859
0
            if (keyboard_next_window || keyboard_prev_window)
12860
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12861
0
        }
12862
12863
    // Gamepad update
12864
54.1k
    g.NavWindowingTimer += io.DeltaTime;
12865
54.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12866
0
    {
12867
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12868
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12869
12870
        // Select window to focus
12871
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12872
0
        if (focus_change_dir != 0)
12873
0
        {
12874
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12875
0
            g.NavWindowingHighlightAlpha = 1.0f;
12876
0
        }
12877
12878
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12879
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12880
0
        {
12881
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12882
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12883
0
                apply_toggle_layer = true;
12884
0
            else if (!g.NavWindowingToggleLayer)
12885
0
                apply_focus_window = g.NavWindowingTarget;
12886
0
            g.NavWindowingTarget = NULL;
12887
0
        }
12888
0
    }
12889
12890
    // Keyboard: Focus
12891
54.1k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12892
0
    {
12893
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12894
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12895
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12896
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12897
0
        if (keyboard_next_window || keyboard_prev_window)
12898
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12899
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12900
0
            apply_focus_window = g.NavWindowingTarget;
12901
0
    }
12902
12903
    // Keyboard: Press and Release ALT to toggle menu layer
12904
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12905
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12906
54.1k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12907
0
    {
12908
0
        g.NavWindowingToggleLayer = true;
12909
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12910
0
    }
12911
54.1k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12912
0
    {
12913
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12914
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12915
        // We cancel toggling nav layer if an owner has claimed the key.
12916
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12917
0
            g.NavWindowingToggleLayer = false;
12918
12919
        // Apply layer toggle on release
12920
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12921
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12922
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12923
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12924
0
                    apply_toggle_layer = true;
12925
0
        if (!IsKeyDown(ImGuiMod_Alt))
12926
0
            g.NavWindowingToggleLayer = false;
12927
0
    }
12928
12929
    // Move window
12930
54.1k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12931
0
    {
12932
0
        ImVec2 nav_move_dir;
12933
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12934
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12935
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12936
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12937
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12938
0
        {
12939
0
            const float NAV_MOVE_SPEED = 800.0f;
12940
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12941
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12942
0
            g.NavDisableMouseHover = true;
12943
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
12944
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12945
0
            {
12946
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12947
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12948
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12949
0
            }
12950
0
        }
12951
0
    }
12952
12953
    // Apply final focus
12954
54.1k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12955
0
    {
12956
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
12957
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
12958
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12959
0
        ClearActiveID();
12960
0
        NavRestoreHighlightAfterMove();
12961
0
        ClosePopupsOverWindow(apply_focus_window, false);
12962
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
12963
0
        apply_focus_window = g.NavWindow;
12964
0
        if (apply_focus_window->NavLastIds[0] == 0)
12965
0
            NavInitWindow(apply_focus_window, false);
12966
12967
        // If the window has ONLY a menu layer (no main layer), select it directly
12968
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12969
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12970
        // the target window as already been previewed once.
12971
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12972
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12973
        // won't be valid.
12974
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12975
0
            g.NavLayer = ImGuiNavLayer_Menu;
12976
12977
        // Request OS level focus
12978
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12979
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12980
0
    }
12981
54.1k
    if (apply_focus_window)
12982
0
        g.NavWindowingTarget = NULL;
12983
12984
    // Apply menu/layer toggle
12985
54.1k
    if (apply_toggle_layer && g.NavWindow)
12986
0
    {
12987
0
        ClearActiveID();
12988
12989
        // Move to parent menu if necessary
12990
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12991
0
        while (new_nav_window->ParentWindow
12992
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12993
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12994
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12995
0
            new_nav_window = new_nav_window->ParentWindow;
12996
0
        if (new_nav_window != g.NavWindow)
12997
0
        {
12998
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12999
0
            FocusWindow(new_nav_window);
13000
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13001
0
        }
13002
13003
        // Toggle layer
13004
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13005
0
        if (new_nav_layer != g.NavLayer)
13006
0
        {
13007
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13008
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13009
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13010
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13011
0
            NavRestoreLayer(new_nav_layer);
13012
0
            NavRestoreHighlightAfterMove();
13013
0
        }
13014
0
    }
13015
54.1k
}
13016
13017
// Window has already passed the IsWindowNavFocusable()
13018
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13019
0
{
13020
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13021
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13022
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13023
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13024
0
    if (window->DockNodeAsHost)
13025
0
        return "(Dock node)"; // Not normally shown to user.
13026
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13027
0
}
13028
13029
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13030
void ImGui::NavUpdateWindowingOverlay()
13031
0
{
13032
0
    ImGuiContext& g = *GImGui;
13033
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13034
13035
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13036
0
        return;
13037
13038
0
    if (g.NavWindowingListWindow == NULL)
13039
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13040
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13041
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13042
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13043
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13044
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13045
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13046
0
    {
13047
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13048
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13049
0
        if (!IsWindowNavFocusable(window))
13050
0
            continue;
13051
0
        const char* label = window->Name;
13052
0
        if (label == FindRenderedTextEnd(label))
13053
0
            label = GetFallbackWindowNameForWindowingList(window);
13054
0
        Selectable(label, g.NavWindowingTarget == window);
13055
0
    }
13056
0
    End();
13057
0
    PopStyleVar();
13058
0
}
13059
13060
13061
//-----------------------------------------------------------------------------
13062
// [SECTION] DRAG AND DROP
13063
//-----------------------------------------------------------------------------
13064
13065
bool ImGui::IsDragDropActive()
13066
0
{
13067
0
    ImGuiContext& g = *GImGui;
13068
0
    return g.DragDropActive;
13069
0
}
13070
13071
void ImGui::ClearDragDrop()
13072
4
{
13073
4
    ImGuiContext& g = *GImGui;
13074
4
    g.DragDropActive = false;
13075
4
    g.DragDropPayload.Clear();
13076
4
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13077
4
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13078
4
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13079
4
    g.DragDropAcceptFrameCount = -1;
13080
13081
4
    g.DragDropPayloadBufHeap.clear();
13082
4
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13083
4
}
13084
13085
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13086
// If the item has an identifier:
13087
// - This assume/require the item to be activated (typically via ButtonBehavior).
13088
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13089
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13090
// If the item has no identifier:
13091
// - Currently always assume left mouse button.
13092
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13093
30
{
13094
30
    ImGuiContext& g = *GImGui;
13095
30
    ImGuiWindow* window = g.CurrentWindow;
13096
13097
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13098
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13099
30
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13100
13101
30
    bool source_drag_active = false;
13102
30
    ImGuiID source_id = 0;
13103
30
    ImGuiID source_parent_id = 0;
13104
30
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13105
30
    {
13106
30
        source_id = g.LastItemData.ID;
13107
30
        if (source_id != 0)
13108
30
        {
13109
            // Common path: items with ID
13110
30
            if (g.ActiveId != source_id)
13111
0
                return false;
13112
30
            if (g.ActiveIdMouseButton != -1)
13113
0
                mouse_button = g.ActiveIdMouseButton;
13114
30
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13115
0
                return false;
13116
30
            g.ActiveIdAllowOverlap = false;
13117
30
        }
13118
0
        else
13119
0
        {
13120
            // Uncommon path: items without ID
13121
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13122
0
                return false;
13123
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13124
0
                return false;
13125
13126
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13127
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13128
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13129
0
            {
13130
0
                IM_ASSERT(0);
13131
0
                return false;
13132
0
            }
13133
13134
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13135
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13136
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13137
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13138
            // Rely on keeping other window->LastItemXXX fields intact.
13139
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13140
0
            KeepAliveID(source_id);
13141
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13142
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13143
0
            {
13144
0
                SetActiveID(source_id, window);
13145
0
                FocusWindow(window);
13146
0
            }
13147
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13148
0
                g.ActiveIdAllowOverlap = is_hovered;
13149
0
        }
13150
30
        if (g.ActiveId != source_id)
13151
0
            return false;
13152
30
        source_parent_id = window->IDStack.back();
13153
30
        source_drag_active = IsMouseDragging(mouse_button);
13154
13155
        // Disable navigation and key inputs while dragging + cancel existing request if any
13156
30
        SetActiveIdUsingAllKeyboardKeys();
13157
30
    }
13158
0
    else
13159
0
    {
13160
0
        window = NULL;
13161
0
        source_id = ImHashStr("#SourceExtern");
13162
0
        source_drag_active = true;
13163
0
    }
13164
13165
30
    if (source_drag_active)
13166
3
    {
13167
3
        if (!g.DragDropActive)
13168
2
        {
13169
2
            IM_ASSERT(source_id != 0);
13170
2
            ClearDragDrop();
13171
2
            ImGuiPayload& payload = g.DragDropPayload;
13172
2
            payload.SourceId = source_id;
13173
2
            payload.SourceParentId = source_parent_id;
13174
2
            g.DragDropActive = true;
13175
2
            g.DragDropSourceFlags = flags;
13176
2
            g.DragDropMouseButton = mouse_button;
13177
2
            if (payload.SourceId == g.ActiveId)
13178
2
                g.ActiveIdNoClearOnFocusLoss = true;
13179
2
        }
13180
3
        g.DragDropSourceFrameCount = g.FrameCount;
13181
3
        g.DragDropWithinSource = true;
13182
13183
3
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13184
0
        {
13185
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13186
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13187
0
            bool ret = BeginTooltip();
13188
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13189
0
            IM_UNUSED(ret);
13190
13191
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13192
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
13193
0
        }
13194
13195
3
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13196
3
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13197
13198
3
        return true;
13199
3
    }
13200
27
    return false;
13201
30
}
13202
13203
void ImGui::EndDragDropSource()
13204
3
{
13205
3
    ImGuiContext& g = *GImGui;
13206
3
    IM_ASSERT(g.DragDropActive);
13207
3
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13208
13209
3
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13210
0
        EndTooltip();
13211
13212
    // Discard the drag if have not called SetDragDropPayload()
13213
3
    if (g.DragDropPayload.DataFrameCount == -1)
13214
0
        ClearDragDrop();
13215
3
    g.DragDropWithinSource = false;
13216
3
}
13217
13218
// Use 'cond' to choose to submit payload on drag start or every frame
13219
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13220
3
{
13221
3
    ImGuiContext& g = *GImGui;
13222
3
    ImGuiPayload& payload = g.DragDropPayload;
13223
3
    if (cond == 0)
13224
3
        cond = ImGuiCond_Always;
13225
13226
3
    IM_ASSERT(type != NULL);
13227
3
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13228
3
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13229
3
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13230
3
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13231
13232
3
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13233
3
    {
13234
        // Copy payload
13235
3
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13236
3
        g.DragDropPayloadBufHeap.resize(0);
13237
3
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13238
0
        {
13239
            // Store in heap
13240
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13241
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13242
0
            memcpy(payload.Data, data, data_size);
13243
0
        }
13244
3
        else if (data_size > 0)
13245
3
        {
13246
            // Store locally
13247
3
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13248
3
            payload.Data = g.DragDropPayloadBufLocal;
13249
3
            memcpy(payload.Data, data, data_size);
13250
3
        }
13251
0
        else
13252
0
        {
13253
0
            payload.Data = NULL;
13254
0
        }
13255
3
        payload.DataSize = (int)data_size;
13256
3
    }
13257
3
    payload.DataFrameCount = g.FrameCount;
13258
13259
    // Return whether the payload has been accepted
13260
3
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13261
3
}
13262
13263
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13264
9
{
13265
9
    ImGuiContext& g = *GImGui;
13266
9
    if (!g.DragDropActive)
13267
0
        return false;
13268
13269
9
    ImGuiWindow* window = g.CurrentWindow;
13270
9
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13271
9
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13272
9
        return false;
13273
0
    IM_ASSERT(id != 0);
13274
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13275
0
        return false;
13276
0
    if (window->SkipItems)
13277
0
        return false;
13278
13279
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13280
0
    g.DragDropTargetRect = bb;
13281
0
    g.DragDropTargetId = id;
13282
0
    g.DragDropWithinTarget = true;
13283
0
    return true;
13284
0
}
13285
13286
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13287
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13288
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13289
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13290
bool ImGui::BeginDragDropTarget()
13291
0
{
13292
0
    ImGuiContext& g = *GImGui;
13293
0
    if (!g.DragDropActive)
13294
0
        return false;
13295
13296
0
    ImGuiWindow* window = g.CurrentWindow;
13297
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13298
0
        return false;
13299
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13300
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13301
0
        return false;
13302
13303
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13304
0
    ImGuiID id = g.LastItemData.ID;
13305
0
    if (id == 0)
13306
0
    {
13307
0
        id = window->GetIDFromRectangle(display_rect);
13308
0
        KeepAliveID(id);
13309
0
    }
13310
0
    if (g.DragDropPayload.SourceId == id)
13311
0
        return false;
13312
13313
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13314
0
    g.DragDropTargetRect = display_rect;
13315
0
    g.DragDropTargetId = id;
13316
0
    g.DragDropWithinTarget = true;
13317
0
    return true;
13318
0
}
13319
13320
bool ImGui::IsDragDropPayloadBeingAccepted()
13321
10
{
13322
10
    ImGuiContext& g = *GImGui;
13323
10
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13324
10
}
13325
13326
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13327
0
{
13328
0
    ImGuiContext& g = *GImGui;
13329
0
    ImGuiWindow* window = g.CurrentWindow;
13330
0
    ImGuiPayload& payload = g.DragDropPayload;
13331
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13332
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13333
0
    if (type != NULL && !payload.IsDataType(type))
13334
0
        return NULL;
13335
13336
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13337
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13338
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13339
0
    ImRect r = g.DragDropTargetRect;
13340
0
    float r_surface = r.GetWidth() * r.GetHeight();
13341
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13342
0
        return NULL;
13343
13344
0
    g.DragDropAcceptFlags = flags;
13345
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13346
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13347
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13348
13349
    // Render default drop visuals
13350
0
    payload.Preview = was_accepted_previously;
13351
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13352
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13353
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13354
13355
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13356
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13357
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13358
0
        return NULL;
13359
13360
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13361
0
    return &payload;
13362
0
}
13363
13364
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13365
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13366
0
{
13367
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13368
0
}
13369
13370
const ImGuiPayload* ImGui::GetDragDropPayload()
13371
0
{
13372
0
    ImGuiContext& g = *GImGui;
13373
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13374
0
}
13375
13376
void ImGui::EndDragDropTarget()
13377
0
{
13378
0
    ImGuiContext& g = *GImGui;
13379
0
    IM_ASSERT(g.DragDropActive);
13380
0
    IM_ASSERT(g.DragDropWithinTarget);
13381
0
    g.DragDropWithinTarget = false;
13382
13383
    // Clear drag and drop state payload right after delivery
13384
0
    if (g.DragDropPayload.Delivery)
13385
0
        ClearDragDrop();
13386
0
}
13387
13388
//-----------------------------------------------------------------------------
13389
// [SECTION] LOGGING/CAPTURING
13390
//-----------------------------------------------------------------------------
13391
// All text output from the interface can be captured into tty/file/clipboard.
13392
// By default, tree nodes are automatically opened during logging.
13393
//-----------------------------------------------------------------------------
13394
13395
// Pass text data straight to log (without being displayed)
13396
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13397
0
{
13398
0
    if (g.LogFile)
13399
0
    {
13400
0
        g.LogBuffer.Buf.resize(0);
13401
0
        g.LogBuffer.appendfv(fmt, args);
13402
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13403
0
    }
13404
0
    else
13405
0
    {
13406
0
        g.LogBuffer.appendfv(fmt, args);
13407
0
    }
13408
0
}
13409
13410
void ImGui::LogText(const char* fmt, ...)
13411
0
{
13412
0
    ImGuiContext& g = *GImGui;
13413
0
    if (!g.LogEnabled)
13414
0
        return;
13415
13416
0
    va_list args;
13417
0
    va_start(args, fmt);
13418
0
    LogTextV(g, fmt, args);
13419
0
    va_end(args);
13420
0
}
13421
13422
void ImGui::LogTextV(const char* fmt, va_list args)
13423
0
{
13424
0
    ImGuiContext& g = *GImGui;
13425
0
    if (!g.LogEnabled)
13426
0
        return;
13427
13428
0
    LogTextV(g, fmt, args);
13429
0
}
13430
13431
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13432
// We split text into individual lines to add current tree level padding
13433
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13434
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13435
0
{
13436
0
    ImGuiContext& g = *GImGui;
13437
0
    ImGuiWindow* window = g.CurrentWindow;
13438
13439
0
    const char* prefix = g.LogNextPrefix;
13440
0
    const char* suffix = g.LogNextSuffix;
13441
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13442
13443
0
    if (!text_end)
13444
0
        text_end = FindRenderedTextEnd(text, text_end);
13445
13446
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13447
0
    if (ref_pos)
13448
0
        g.LogLinePosY = ref_pos->y;
13449
0
    if (log_new_line)
13450
0
    {
13451
0
        LogText(IM_NEWLINE);
13452
0
        g.LogLineFirstItem = true;
13453
0
    }
13454
13455
0
    if (prefix)
13456
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13457
13458
    // Re-adjust padding if we have popped out of our starting depth
13459
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13460
0
        g.LogDepthRef = window->DC.TreeDepth;
13461
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13462
13463
0
    const char* text_remaining = text;
13464
0
    for (;;)
13465
0
    {
13466
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13467
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13468
0
        const char* line_start = text_remaining;
13469
0
        const char* line_end = ImStreolRange(line_start, text_end);
13470
0
        const bool is_last_line = (line_end == text_end);
13471
0
        if (line_start != line_end || !is_last_line)
13472
0
        {
13473
0
            const int line_length = (int)(line_end - line_start);
13474
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13475
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13476
0
            g.LogLineFirstItem = false;
13477
0
            if (*line_end == '\n')
13478
0
            {
13479
0
                LogText(IM_NEWLINE);
13480
0
                g.LogLineFirstItem = true;
13481
0
            }
13482
0
        }
13483
0
        if (is_last_line)
13484
0
            break;
13485
0
        text_remaining = line_end + 1;
13486
0
    }
13487
13488
0
    if (suffix)
13489
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13490
0
}
13491
13492
// Start logging/capturing text output
13493
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13494
0
{
13495
0
    ImGuiContext& g = *GImGui;
13496
0
    ImGuiWindow* window = g.CurrentWindow;
13497
0
    IM_ASSERT(g.LogEnabled == false);
13498
0
    IM_ASSERT(g.LogFile == NULL);
13499
0
    IM_ASSERT(g.LogBuffer.empty());
13500
0
    g.LogEnabled = true;
13501
0
    g.LogType = type;
13502
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13503
0
    g.LogDepthRef = window->DC.TreeDepth;
13504
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13505
0
    g.LogLinePosY = FLT_MAX;
13506
0
    g.LogLineFirstItem = true;
13507
0
}
13508
13509
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13510
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13511
0
{
13512
0
    ImGuiContext& g = *GImGui;
13513
0
    g.LogNextPrefix = prefix;
13514
0
    g.LogNextSuffix = suffix;
13515
0
}
13516
13517
void ImGui::LogToTTY(int auto_open_depth)
13518
0
{
13519
0
    ImGuiContext& g = *GImGui;
13520
0
    if (g.LogEnabled)
13521
0
        return;
13522
0
    IM_UNUSED(auto_open_depth);
13523
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13524
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13525
0
    g.LogFile = stdout;
13526
0
#endif
13527
0
}
13528
13529
// Start logging/capturing text output to given file
13530
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13531
0
{
13532
0
    ImGuiContext& g = *GImGui;
13533
0
    if (g.LogEnabled)
13534
0
        return;
13535
13536
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13537
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13538
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13539
0
    if (!filename)
13540
0
        filename = g.IO.LogFilename;
13541
0
    if (!filename || !filename[0])
13542
0
        return;
13543
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13544
0
    if (!f)
13545
0
    {
13546
0
        IM_ASSERT(0);
13547
0
        return;
13548
0
    }
13549
13550
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13551
0
    g.LogFile = f;
13552
0
}
13553
13554
// Start logging/capturing text output to clipboard
13555
void ImGui::LogToClipboard(int auto_open_depth)
13556
0
{
13557
0
    ImGuiContext& g = *GImGui;
13558
0
    if (g.LogEnabled)
13559
0
        return;
13560
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13561
0
}
13562
13563
void ImGui::LogToBuffer(int auto_open_depth)
13564
0
{
13565
0
    ImGuiContext& g = *GImGui;
13566
0
    if (g.LogEnabled)
13567
0
        return;
13568
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13569
0
}
13570
13571
void ImGui::LogFinish()
13572
108k
{
13573
108k
    ImGuiContext& g = *GImGui;
13574
108k
    if (!g.LogEnabled)
13575
108k
        return;
13576
13577
0
    LogText(IM_NEWLINE);
13578
0
    switch (g.LogType)
13579
0
    {
13580
0
    case ImGuiLogType_TTY:
13581
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13582
0
        fflush(g.LogFile);
13583
0
#endif
13584
0
        break;
13585
0
    case ImGuiLogType_File:
13586
0
        ImFileClose(g.LogFile);
13587
0
        break;
13588
0
    case ImGuiLogType_Buffer:
13589
0
        break;
13590
0
    case ImGuiLogType_Clipboard:
13591
0
        if (!g.LogBuffer.empty())
13592
0
            SetClipboardText(g.LogBuffer.begin());
13593
0
        break;
13594
0
    case ImGuiLogType_None:
13595
0
        IM_ASSERT(0);
13596
0
        break;
13597
0
    }
13598
13599
0
    g.LogEnabled = false;
13600
0
    g.LogType = ImGuiLogType_None;
13601
0
    g.LogFile = NULL;
13602
0
    g.LogBuffer.clear();
13603
0
}
13604
13605
// Helper to display logging buttons
13606
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13607
void ImGui::LogButtons()
13608
0
{
13609
0
    ImGuiContext& g = *GImGui;
13610
13611
0
    PushID("LogButtons");
13612
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13613
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13614
#else
13615
    const bool log_to_tty = false;
13616
#endif
13617
0
    const bool log_to_file = Button("Log To File"); SameLine();
13618
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13619
0
    PushTabStop(false);
13620
0
    SetNextItemWidth(80.0f);
13621
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13622
0
    PopTabStop();
13623
0
    PopID();
13624
13625
    // Start logging at the end of the function so that the buttons don't appear in the log
13626
0
    if (log_to_tty)
13627
0
        LogToTTY();
13628
0
    if (log_to_file)
13629
0
        LogToFile();
13630
0
    if (log_to_clipboard)
13631
0
        LogToClipboard();
13632
0
}
13633
13634
13635
//-----------------------------------------------------------------------------
13636
// [SECTION] SETTINGS
13637
//-----------------------------------------------------------------------------
13638
// - UpdateSettings() [Internal]
13639
// - MarkIniSettingsDirty() [Internal]
13640
// - FindSettingsHandler() [Internal]
13641
// - ClearIniSettings() [Internal]
13642
// - LoadIniSettingsFromDisk()
13643
// - LoadIniSettingsFromMemory()
13644
// - SaveIniSettingsToDisk()
13645
// - SaveIniSettingsToMemory()
13646
//-----------------------------------------------------------------------------
13647
// - CreateNewWindowSettings() [Internal]
13648
// - FindWindowSettingsByID() [Internal]
13649
// - FindWindowSettingsByWindow() [Internal]
13650
// - ClearWindowSettings() [Internal]
13651
// - WindowSettingsHandler_***() [Internal]
13652
//-----------------------------------------------------------------------------
13653
13654
// Called by NewFrame()
13655
void ImGui::UpdateSettings()
13656
54.1k
{
13657
    // Load settings on first frame (if not explicitly loaded manually before)
13658
54.1k
    ImGuiContext& g = *GImGui;
13659
54.1k
    if (!g.SettingsLoaded)
13660
1
    {
13661
1
        IM_ASSERT(g.SettingsWindows.empty());
13662
1
        if (g.IO.IniFilename)
13663
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13664
1
        g.SettingsLoaded = true;
13665
1
    }
13666
13667
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13668
54.1k
    if (g.SettingsDirtyTimer > 0.0f)
13669
1.20k
    {
13670
1.20k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13671
1.20k
        if (g.SettingsDirtyTimer <= 0.0f)
13672
4
        {
13673
4
            if (g.IO.IniFilename != NULL)
13674
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13675
4
            else
13676
4
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13677
4
            g.SettingsDirtyTimer = 0.0f;
13678
4
        }
13679
1.20k
    }
13680
54.1k
}
13681
13682
void ImGui::MarkIniSettingsDirty()
13683
0
{
13684
0
    ImGuiContext& g = *GImGui;
13685
0
    if (g.SettingsDirtyTimer <= 0.0f)
13686
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13687
0
}
13688
13689
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13690
9.32k
{
13691
9.32k
    ImGuiContext& g = *GImGui;
13692
9.32k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13693
12
        if (g.SettingsDirtyTimer <= 0.0f)
13694
4
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13695
9.32k
}
13696
13697
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13698
2
{
13699
2
    ImGuiContext& g = *GImGui;
13700
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13701
2
    g.SettingsHandlers.push_back(*handler);
13702
2
}
13703
13704
void ImGui::RemoveSettingsHandler(const char* type_name)
13705
0
{
13706
0
    ImGuiContext& g = *GImGui;
13707
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13708
0
        g.SettingsHandlers.erase(handler);
13709
0
}
13710
13711
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13712
2
{
13713
2
    ImGuiContext& g = *GImGui;
13714
2
    const ImGuiID type_hash = ImHashStr(type_name);
13715
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13716
1
        if (handler.TypeHash == type_hash)
13717
0
            return &handler;
13718
2
    return NULL;
13719
2
}
13720
13721
// Clear all settings (windows, tables, docking etc.)
13722
void ImGui::ClearIniSettings()
13723
0
{
13724
0
    ImGuiContext& g = *GImGui;
13725
0
    g.SettingsIniData.clear();
13726
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13727
0
        if (handler.ClearAllFn != NULL)
13728
0
            handler.ClearAllFn(&g, &handler);
13729
0
}
13730
13731
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13732
0
{
13733
0
    size_t file_data_size = 0;
13734
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13735
0
    if (!file_data)
13736
0
        return;
13737
0
    if (file_data_size > 0)
13738
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13739
0
    IM_FREE(file_data);
13740
0
}
13741
13742
// Zero-tolerance, no error reporting, cheap .ini parsing
13743
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13744
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13745
0
{
13746
0
    ImGuiContext& g = *GImGui;
13747
0
    IM_ASSERT(g.Initialized);
13748
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13749
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13750
13751
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13752
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13753
0
    if (ini_size == 0)
13754
0
        ini_size = strlen(ini_data);
13755
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13756
0
    char* const buf = g.SettingsIniData.Buf.Data;
13757
0
    char* const buf_end = buf + ini_size;
13758
0
    memcpy(buf, ini_data, ini_size);
13759
0
    buf_end[0] = 0;
13760
13761
    // Call pre-read handlers
13762
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13763
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13764
0
        if (handler.ReadInitFn != NULL)
13765
0
            handler.ReadInitFn(&g, &handler);
13766
13767
0
    void* entry_data = NULL;
13768
0
    ImGuiSettingsHandler* entry_handler = NULL;
13769
13770
0
    char* line_end = NULL;
13771
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13772
0
    {
13773
        // Skip new lines markers, then find end of the line
13774
0
        while (*line == '\n' || *line == '\r')
13775
0
            line++;
13776
0
        line_end = line;
13777
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13778
0
            line_end++;
13779
0
        line_end[0] = 0;
13780
0
        if (line[0] == ';')
13781
0
            continue;
13782
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13783
0
        {
13784
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13785
0
            line_end[-1] = 0;
13786
0
            const char* name_end = line_end - 1;
13787
0
            const char* type_start = line + 1;
13788
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13789
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13790
0
            if (!type_end || !name_start)
13791
0
                continue;
13792
0
            *type_end = 0; // Overwrite first ']'
13793
0
            name_start++;  // Skip second '['
13794
0
            entry_handler = FindSettingsHandler(type_start);
13795
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13796
0
        }
13797
0
        else if (entry_handler != NULL && entry_data != NULL)
13798
0
        {
13799
            // Let type handler parse the line
13800
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13801
0
        }
13802
0
    }
13803
0
    g.SettingsLoaded = true;
13804
13805
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13806
0
    memcpy(buf, ini_data, ini_size);
13807
13808
    // Call post-read handlers
13809
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13810
0
        if (handler.ApplyAllFn != NULL)
13811
0
            handler.ApplyAllFn(&g, &handler);
13812
0
}
13813
13814
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13815
0
{
13816
0
    ImGuiContext& g = *GImGui;
13817
0
    g.SettingsDirtyTimer = 0.0f;
13818
0
    if (!ini_filename)
13819
0
        return;
13820
13821
0
    size_t ini_data_size = 0;
13822
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13823
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13824
0
    if (!f)
13825
0
        return;
13826
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13827
0
    ImFileClose(f);
13828
0
}
13829
13830
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13831
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13832
0
{
13833
0
    ImGuiContext& g = *GImGui;
13834
0
    g.SettingsDirtyTimer = 0.0f;
13835
0
    g.SettingsIniData.Buf.resize(0);
13836
0
    g.SettingsIniData.Buf.push_back(0);
13837
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13838
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
13839
0
    if (out_size)
13840
0
        *out_size = (size_t)g.SettingsIniData.size();
13841
0
    return g.SettingsIniData.c_str();
13842
0
}
13843
13844
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13845
0
{
13846
0
    ImGuiContext& g = *GImGui;
13847
13848
0
    if (g.IO.ConfigDebugIniSettings == false)
13849
0
    {
13850
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13851
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
13852
0
        if (const char* p = strstr(name, "###"))
13853
0
            name = p;
13854
0
    }
13855
0
    const size_t name_len = strlen(name);
13856
13857
    // Allocate chunk
13858
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13859
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13860
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13861
0
    settings->ID = ImHashStr(name, name_len);
13862
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13863
13864
0
    return settings;
13865
0
}
13866
13867
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13868
// This is called once per window .ini entry + once per newly instantiated window.
13869
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13870
2
{
13871
2
    ImGuiContext& g = *GImGui;
13872
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13873
0
        if (settings->ID == id && !settings->WantDelete)
13874
0
            return settings;
13875
2
    return NULL;
13876
2
}
13877
13878
// This is faster if you are holding on a Window already as we don't need to perform a search.
13879
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13880
2
{
13881
2
    ImGuiContext& g = *GImGui;
13882
2
    if (window->SettingsOffset != -1)
13883
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13884
2
    return FindWindowSettingsByID(window->ID);
13885
2
}
13886
13887
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13888
void ImGui::ClearWindowSettings(const char* name)
13889
0
{
13890
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13891
0
    ImGuiContext& g = *GImGui;
13892
0
    ImGuiWindow* window = FindWindowByName(name);
13893
0
    if (window != NULL)
13894
0
    {
13895
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13896
0
        InitOrLoadWindowSettings(window, NULL);
13897
0
        if (window->DockId != 0)
13898
0
            DockContextProcessUndockWindow(&g, window, true);
13899
0
    }
13900
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13901
0
        settings->WantDelete = true;
13902
0
}
13903
13904
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13905
0
{
13906
0
    ImGuiContext& g = *ctx;
13907
0
    for (ImGuiWindow* window : g.Windows)
13908
0
        window->SettingsOffset = -1;
13909
0
    g.SettingsWindows.clear();
13910
0
}
13911
13912
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13913
0
{
13914
0
    ImGuiID id = ImHashStr(name);
13915
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13916
0
    if (settings)
13917
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13918
0
    else
13919
0
        settings = ImGui::CreateNewWindowSettings(name);
13920
0
    settings->ID = id;
13921
0
    settings->WantApply = true;
13922
0
    return (void*)settings;
13923
0
}
13924
13925
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13926
0
{
13927
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13928
0
    int x, y;
13929
0
    int i;
13930
0
    ImU32 u1;
13931
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13932
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13933
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13934
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13935
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13936
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13937
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13938
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13939
0
}
13940
13941
// Apply to existing windows (if any)
13942
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13943
0
{
13944
0
    ImGuiContext& g = *ctx;
13945
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13946
0
        if (settings->WantApply)
13947
0
        {
13948
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13949
0
                ApplyWindowSettings(window, settings);
13950
0
            settings->WantApply = false;
13951
0
        }
13952
0
}
13953
13954
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13955
0
{
13956
    // Gather data from windows that were active during this session
13957
    // (if a window wasn't opened in this session we preserve its settings)
13958
0
    ImGuiContext& g = *ctx;
13959
0
    for (ImGuiWindow* window : g.Windows)
13960
0
    {
13961
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13962
0
            continue;
13963
13964
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13965
0
        if (!settings)
13966
0
        {
13967
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13968
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13969
0
        }
13970
0
        IM_ASSERT(settings->ID == window->ID);
13971
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13972
0
        settings->Size = ImVec2ih(window->SizeFull);
13973
0
        settings->ViewportId = window->ViewportId;
13974
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13975
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13976
0
        settings->DockId = window->DockId;
13977
0
        settings->ClassId = window->WindowClass.ClassId;
13978
0
        settings->DockOrder = window->DockOrder;
13979
0
        settings->Collapsed = window->Collapsed;
13980
0
        settings->WantDelete = false;
13981
0
    }
13982
13983
    // Write to text buffer
13984
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13985
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13986
0
    {
13987
0
        if (settings->WantDelete)
13988
0
            continue;
13989
0
        const char* settings_name = settings->GetName();
13990
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13991
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13992
0
        {
13993
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13994
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13995
0
        }
13996
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13997
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13998
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13999
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14000
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
14001
0
        if (settings->DockId != 0)
14002
0
        {
14003
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14004
0
            if (settings->DockOrder == -1)
14005
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
14006
0
            else
14007
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14008
0
            if (settings->ClassId != 0)
14009
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14010
0
        }
14011
0
        buf->append("\n");
14012
0
    }
14013
0
}
14014
14015
14016
//-----------------------------------------------------------------------------
14017
// [SECTION] LOCALIZATION
14018
//-----------------------------------------------------------------------------
14019
14020
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14021
1
{
14022
1
    ImGuiContext& g = *GImGui;
14023
11
    for (int n = 0; n < count; n++)
14024
10
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14025
1
}
14026
14027
14028
//-----------------------------------------------------------------------------
14029
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14030
//-----------------------------------------------------------------------------
14031
// - GetMainViewport()
14032
// - FindViewportByID()
14033
// - FindViewportByPlatformHandle()
14034
// - SetCurrentViewport() [Internal]
14035
// - SetWindowViewport() [Internal]
14036
// - GetWindowAlwaysWantOwnViewport() [Internal]
14037
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14038
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14039
// - TranslateWindowsInViewport() [Internal]
14040
// - ScaleWindowsInViewport() [Internal]
14041
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14042
// - UpdateViewportsNewFrame() [Internal]
14043
// - UpdateViewportsEndFrame() [Internal]
14044
// - AddUpdateViewport() [Internal]
14045
// - WindowSelectViewport() [Internal]
14046
// - WindowSyncOwnedViewport() [Internal]
14047
// - UpdatePlatformWindows()
14048
// - RenderPlatformWindowsDefault()
14049
// - FindPlatformMonitorForPos() [Internal]
14050
// - FindPlatformMonitorForRect() [Internal]
14051
// - UpdateViewportPlatformMonitor() [Internal]
14052
// - DestroyPlatformWindow() [Internal]
14053
// - DestroyPlatformWindows()
14054
//-----------------------------------------------------------------------------
14055
14056
ImGuiViewport* ImGui::GetMainViewport()
14057
159k
{
14058
159k
    ImGuiContext& g = *GImGui;
14059
159k
    return g.Viewports[0];
14060
159k
}
14061
14062
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14063
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14064
54.1k
{
14065
54.1k
    ImGuiContext& g = *GImGui;
14066
54.1k
    for (ImGuiViewportP* viewport : g.Viewports)
14067
54.1k
        if (viewport->ID == id)
14068
54.1k
            return viewport;
14069
0
    return NULL;
14070
54.1k
}
14071
14072
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14073
0
{
14074
0
    ImGuiContext& g = *GImGui;
14075
0
    for (ImGuiViewportP* viewport : g.Viewports)
14076
0
        if (viewport->PlatformHandle == platform_handle)
14077
0
            return viewport;
14078
0
    return NULL;
14079
0
}
14080
14081
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14082
318k
{
14083
318k
    ImGuiContext& g = *GImGui;
14084
318k
    (void)current_window;
14085
14086
318k
    if (viewport)
14087
264k
        viewport->LastFrameActive = g.FrameCount;
14088
318k
    if (g.CurrentViewport == viewport)
14089
210k
        return;
14090
108k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14091
108k
    g.CurrentViewport = viewport;
14092
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14093
14094
    // Notify platform layer of viewport changes
14095
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14096
108k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14097
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14098
108k
}
14099
14100
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14101
159k
{
14102
    // Abandon viewport
14103
159k
    if (window->ViewportOwned && window->Viewport->Window == window)
14104
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14105
14106
159k
    window->Viewport = viewport;
14107
159k
    window->ViewportId = viewport->ID;
14108
159k
    window->ViewportOwned = (viewport->Window == window);
14109
159k
}
14110
14111
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14112
0
{
14113
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14114
0
    ImGuiContext& g = *GImGui;
14115
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14116
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14117
0
            if (!window->DockIsActive)
14118
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14119
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14120
0
                        return true;
14121
0
    return false;
14122
0
}
14123
14124
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14125
0
{
14126
0
    ImGuiContext& g = *GImGui;
14127
0
    if (window->Viewport == viewport)
14128
0
        return false;
14129
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14130
0
        return false;
14131
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14132
0
        return false;
14133
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14134
0
        return false;
14135
0
    if (GetWindowAlwaysWantOwnViewport(window))
14136
0
        return false;
14137
14138
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14139
0
    for (ImGuiWindow* window_behind : g.Windows)
14140
0
    {
14141
0
        if (window_behind == window)
14142
0
            break;
14143
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14144
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14145
0
                return false;
14146
0
    }
14147
14148
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14149
0
    ImGuiViewportP* old_viewport = window->Viewport;
14150
0
    if (window->ViewportOwned)
14151
0
        for (int n = 0; n < g.Windows.Size; n++)
14152
0
            if (g.Windows[n]->Viewport == old_viewport)
14153
0
                SetWindowViewport(g.Windows[n], viewport);
14154
0
    SetWindowViewport(window, viewport);
14155
0
    BringWindowToDisplayFront(window);
14156
14157
0
    return true;
14158
0
}
14159
14160
// FIXME: handle 0 to N host viewports
14161
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14162
0
{
14163
0
    ImGuiContext& g = *GImGui;
14164
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14165
0
}
14166
14167
// Translate Dear ImGui windows when a Host Viewport has been moved
14168
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14169
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14170
0
{
14171
0
    ImGuiContext& g = *GImGui;
14172
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14173
14174
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14175
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14176
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14177
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14178
    // and so the window will appear to teleport when releasing the mouse.
14179
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14180
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14181
0
    ImVec2 delta_pos = new_pos - old_pos;
14182
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14183
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14184
0
            TranslateWindow(window, delta_pos);
14185
0
}
14186
14187
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14188
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14189
0
{
14190
0
    ImGuiContext& g = *GImGui;
14191
0
    if (viewport->Window)
14192
0
    {
14193
0
        ScaleWindow(viewport->Window, scale);
14194
0
    }
14195
0
    else
14196
0
    {
14197
0
        for (ImGuiWindow* window : g.Windows)
14198
0
            if (window->Viewport == viewport)
14199
0
                ScaleWindow(window, scale);
14200
0
    }
14201
0
}
14202
14203
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14204
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14205
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14206
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14207
0
{
14208
0
    ImGuiContext& g = *GImGui;
14209
0
    ImGuiViewportP* best_candidate = NULL;
14210
0
    for (ImGuiViewportP* viewport : g.Viewports)
14211
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14212
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14213
0
                best_candidate = viewport;
14214
0
    return best_candidate;
14215
0
}
14216
14217
// Update viewports and monitor infos
14218
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14219
static void ImGui::UpdateViewportsNewFrame()
14220
54.1k
{
14221
54.1k
    ImGuiContext& g = *GImGui;
14222
54.1k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14223
14224
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14225
    // Update Focused status
14226
54.1k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14227
54.1k
    if (viewports_enabled)
14228
0
    {
14229
0
        ImGuiViewportP* focused_viewport = NULL;
14230
0
        for (ImGuiViewportP* viewport : g.Viewports)
14231
0
        {
14232
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14233
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14234
0
            {
14235
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14236
0
                if (is_minimized)
14237
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14238
0
                else
14239
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14240
0
            }
14241
14242
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14243
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14244
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14245
0
            {
14246
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14247
0
                if (is_focused)
14248
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14249
0
                else
14250
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14251
0
                if (is_focused)
14252
0
                    focused_viewport = viewport;
14253
0
            }
14254
0
        }
14255
14256
        // Focused viewport has changed?
14257
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14258
0
        {
14259
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14260
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14261
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14262
14263
            // Store a tag so we can infer z-order easily from all our windows
14264
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14265
            // will keep the front most stamp instead of losing it back to their parent viewport.
14266
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14267
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14268
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14269
14270
            // Focus associated dear imgui window
14271
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14272
            // - if focus didn't happen because we destroyed another window (#6462)
14273
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14274
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14275
0
            if (apply_imgui_focus_on_focused_viewport)
14276
0
            {
14277
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14278
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14279
0
                if (focused_viewport->Window != NULL)
14280
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14281
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14282
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14283
0
                else
14284
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14285
0
            }
14286
0
        }
14287
0
        if (focused_viewport)
14288
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14289
0
    }
14290
14291
    // Create/update main viewport with current platform position.
14292
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14293
54.1k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14294
54.1k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14295
54.1k
    IM_ASSERT(main_viewport->Window == NULL);
14296
54.1k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14297
54.1k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14298
54.1k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14299
0
    {
14300
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14301
0
        main_viewport_size = main_viewport->Size;
14302
0
    }
14303
54.1k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14304
14305
54.1k
    g.CurrentDpiScale = 0.0f;
14306
54.1k
    g.CurrentViewport = NULL;
14307
54.1k
    g.MouseViewport = NULL;
14308
108k
    for (int n = 0; n < g.Viewports.Size; n++)
14309
54.1k
    {
14310
54.1k
        ImGuiViewportP* viewport = g.Viewports[n];
14311
54.1k
        viewport->Idx = n;
14312
14313
        // Erase unused viewports
14314
54.1k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14315
0
        {
14316
0
            DestroyViewport(viewport);
14317
0
            n--;
14318
0
            continue;
14319
0
        }
14320
14321
54.1k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14322
54.1k
        if (viewports_enabled)
14323
0
        {
14324
            // Update Position and Size (from Platform Window to ImGui) if requested.
14325
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14326
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14327
0
            {
14328
                // Viewport->WorkPos and WorkSize will be updated below
14329
0
                if (viewport->PlatformRequestMove)
14330
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14331
0
                if (viewport->PlatformRequestResize)
14332
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14333
0
            }
14334
0
        }
14335
14336
        // Update/copy monitor info
14337
54.1k
        UpdateViewportPlatformMonitor(viewport);
14338
14339
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14340
54.1k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14341
54.1k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14342
54.1k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14343
54.1k
        viewport->UpdateWorkRect();
14344
14345
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14346
54.1k
        viewport->Alpha = 1.0f;
14347
14348
        // Translate Dear ImGui windows when a Host Viewport has been moved
14349
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14350
54.1k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14351
54.1k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14352
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14353
14354
        // Update DPI scale
14355
54.1k
        float new_dpi_scale;
14356
54.1k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14357
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14358
54.1k
        else if (viewport->PlatformMonitor != -1)
14359
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14360
54.1k
        else
14361
54.1k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14362
54.1k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14363
0
        {
14364
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14365
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14366
0
                ScaleWindowsInViewport(viewport, scale_factor);
14367
            //if (viewport == GetMainViewport())
14368
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14369
14370
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14371
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14372
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14373
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14374
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14375
0
        }
14376
54.1k
        viewport->DpiScale = new_dpi_scale;
14377
54.1k
    }
14378
14379
    // Update fallback monitor
14380
54.1k
    if (g.PlatformIO.Monitors.Size == 0)
14381
54.1k
    {
14382
54.1k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14383
54.1k
        monitor->MainPos = main_viewport->Pos;
14384
54.1k
        monitor->MainSize = main_viewport->Size;
14385
54.1k
        monitor->WorkPos = main_viewport->WorkPos;
14386
54.1k
        monitor->WorkSize = main_viewport->WorkSize;
14387
54.1k
        monitor->DpiScale = main_viewport->DpiScale;
14388
54.1k
    }
14389
14390
54.1k
    if (!viewports_enabled)
14391
54.1k
    {
14392
54.1k
        g.MouseViewport = main_viewport;
14393
54.1k
        return;
14394
54.1k
    }
14395
14396
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14397
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14398
0
    ImGuiViewportP* viewport_hovered = NULL;
14399
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14400
0
    {
14401
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14402
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14403
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14404
0
    }
14405
0
    else
14406
0
    {
14407
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14408
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14409
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14410
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14411
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14412
0
    }
14413
0
    if (viewport_hovered != NULL)
14414
0
        g.MouseLastHoveredViewport = viewport_hovered;
14415
0
    else if (g.MouseLastHoveredViewport == NULL)
14416
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14417
14418
    // Update mouse reference viewport
14419
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14420
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14421
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14422
0
        g.MouseViewport = g.MovingWindow->Viewport;
14423
0
    else
14424
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14425
14426
    // When dragging something, always refer to the last hovered viewport.
14427
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14428
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14429
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14430
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14431
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14432
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14433
0
        viewport_hovered = g.MouseLastHoveredViewport;
14434
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14435
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14436
0
            g.MouseViewport = viewport_hovered;
14437
14438
0
    IM_ASSERT(g.MouseViewport != NULL);
14439
0
}
14440
14441
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14442
static void ImGui::UpdateViewportsEndFrame()
14443
54.1k
{
14444
54.1k
    ImGuiContext& g = *GImGui;
14445
54.1k
    g.PlatformIO.Viewports.resize(0);
14446
108k
    for (int i = 0; i < g.Viewports.Size; i++)
14447
54.1k
    {
14448
54.1k
        ImGuiViewportP* viewport = g.Viewports[i];
14449
54.1k
        viewport->LastPos = viewport->Pos;
14450
54.1k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14451
0
            if (i > 0) // Always include main viewport in the list
14452
0
                continue;
14453
54.1k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14454
0
            continue;
14455
54.1k
        if (i > 0)
14456
54.1k
            IM_ASSERT(viewport->Window != NULL);
14457
54.1k
        g.PlatformIO.Viewports.push_back(viewport);
14458
54.1k
    }
14459
54.1k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14460
54.1k
}
14461
14462
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14463
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14464
54.1k
{
14465
54.1k
    ImGuiContext& g = *GImGui;
14466
54.1k
    IM_ASSERT(id != 0);
14467
14468
54.1k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14469
54.1k
    if (window != NULL)
14470
0
    {
14471
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14472
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14473
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14474
0
            flags |= ImGuiViewportFlags_NoInputs;
14475
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14476
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14477
0
    }
14478
14479
54.1k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14480
54.1k
    if (viewport)
14481
54.1k
    {
14482
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14483
54.1k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14484
54.1k
            viewport->Pos = pos;
14485
54.1k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14486
54.1k
            viewport->Size = size;
14487
54.1k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14488
54.1k
    }
14489
0
    else
14490
0
    {
14491
        // New viewport
14492
0
        viewport = IM_NEW(ImGuiViewportP)();
14493
0
        viewport->ID = id;
14494
0
        viewport->Idx = g.Viewports.Size;
14495
0
        viewport->Pos = viewport->LastPos = pos;
14496
0
        viewport->Size = size;
14497
0
        viewport->Flags = flags;
14498
0
        UpdateViewportPlatformMonitor(viewport);
14499
0
        g.Viewports.push_back(viewport);
14500
0
        g.ViewportCreatedCount++;
14501
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14502
14503
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14504
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14505
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14506
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14507
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14508
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14509
14510
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14511
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14512
0
        if (viewport->PlatformMonitor != -1)
14513
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14514
0
    }
14515
14516
54.1k
    viewport->Window = window;
14517
54.1k
    viewport->LastFrameActive = g.FrameCount;
14518
54.1k
    viewport->UpdateWorkRect();
14519
54.1k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14520
14521
54.1k
    if (window != NULL)
14522
0
        window->ViewportOwned = true;
14523
14524
54.1k
    return viewport;
14525
54.1k
}
14526
14527
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14528
0
{
14529
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14530
0
    ImGuiContext& g = *GImGui;
14531
0
    for (ImGuiWindow* window : g.Windows)
14532
0
    {
14533
0
        if (window->Viewport != viewport)
14534
0
            continue;
14535
0
        window->Viewport = NULL;
14536
0
        window->ViewportOwned = false;
14537
0
    }
14538
0
    if (viewport == g.MouseLastHoveredViewport)
14539
0
        g.MouseLastHoveredViewport = NULL;
14540
14541
    // Destroy
14542
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14543
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14544
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14545
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14546
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14547
0
    IM_DELETE(viewport);
14548
0
}
14549
14550
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14551
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14552
159k
{
14553
159k
    ImGuiContext& g = *GImGui;
14554
159k
    ImGuiWindowFlags flags = window->Flags;
14555
159k
    window->ViewportAllowPlatformMonitorExtend = -1;
14556
14557
    // Restore main viewport if multi-viewport is not supported by the backend
14558
159k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14559
159k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14560
159k
    {
14561
159k
        SetWindowViewport(window, main_viewport);
14562
159k
        return;
14563
159k
    }
14564
0
    window->ViewportOwned = false;
14565
14566
    // Appearing popups reset their viewport so they can inherit again
14567
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14568
0
    {
14569
0
        window->Viewport = NULL;
14570
0
        window->ViewportId = 0;
14571
0
    }
14572
14573
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14574
0
    {
14575
        // By default inherit from parent window
14576
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14577
0
            window->Viewport = window->ParentWindow->Viewport;
14578
14579
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14580
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14581
0
        {
14582
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14583
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14584
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14585
0
        }
14586
0
    }
14587
14588
0
    bool lock_viewport = false;
14589
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14590
0
    {
14591
        // Code explicitly request a viewport
14592
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14593
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14594
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
14595
0
        {
14596
0
            window->Viewport->Window = window;
14597
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
14598
0
        }
14599
0
        lock_viewport = true;
14600
0
    }
14601
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14602
0
    {
14603
        // Always inherit viewport from parent window
14604
0
        if (window->DockNode && window->DockNode->HostWindow)
14605
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14606
0
        window->Viewport = window->ParentWindow->Viewport;
14607
0
    }
14608
0
    else if (window->DockNode && window->DockNode->HostWindow)
14609
0
    {
14610
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14611
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14612
0
    }
14613
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14614
0
    {
14615
0
        window->Viewport = g.MouseViewport;
14616
0
    }
14617
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14618
0
    {
14619
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14620
0
    }
14621
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14622
0
    {
14623
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14624
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14625
0
    }
14626
0
    else
14627
0
    {
14628
        // Merge into host viewport?
14629
        // We cannot test window->ViewportOwned as it set lower in the function.
14630
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14631
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14632
0
        if (try_to_merge_into_host_viewport)
14633
0
            UpdateTryMergeWindowIntoHostViewports(window);
14634
0
    }
14635
14636
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14637
0
    if (window->Viewport == NULL)
14638
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14639
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14640
14641
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14642
0
    if (!lock_viewport)
14643
0
    {
14644
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14645
0
        {
14646
            // We need to take account of the possibility that mouse may become invalid.
14647
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14648
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14649
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14650
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14651
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14652
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14653
0
            else
14654
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14655
0
        }
14656
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14657
0
        {
14658
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14659
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14660
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14661
0
            {
14662
                // Steal/transfer ownership
14663
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14664
0
                window->Viewport->Window = window;
14665
0
                window->Viewport->ID = window->ID;
14666
0
                window->Viewport->LastNameHash = 0;
14667
0
            }
14668
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14669
0
            {
14670
                // New viewport
14671
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14672
0
            }
14673
0
        }
14674
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14675
0
        {
14676
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14677
            // Child windows are kept contained within their parent.
14678
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14679
0
        }
14680
0
    }
14681
14682
    // Update flags
14683
0
    window->ViewportOwned = (window == window->Viewport->Window);
14684
0
    window->ViewportId = window->Viewport->ID;
14685
14686
    // If the OS window has a title bar, hide our imgui title bar
14687
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14688
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14689
0
}
14690
14691
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14692
0
{
14693
0
    ImGuiContext& g = *GImGui;
14694
14695
0
    bool viewport_rect_changed = false;
14696
14697
    // Synchronize window --> viewport in most situations
14698
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14699
0
    if (window->Viewport->PlatformRequestMove)
14700
0
    {
14701
0
        window->Pos = window->Viewport->Pos;
14702
0
        MarkIniSettingsDirty(window);
14703
0
    }
14704
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14705
0
    {
14706
0
        viewport_rect_changed = true;
14707
0
        window->Viewport->Pos = window->Pos;
14708
0
    }
14709
14710
0
    if (window->Viewport->PlatformRequestResize)
14711
0
    {
14712
0
        window->Size = window->SizeFull = window->Viewport->Size;
14713
0
        MarkIniSettingsDirty(window);
14714
0
    }
14715
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14716
0
    {
14717
0
        viewport_rect_changed = true;
14718
0
        window->Viewport->Size = window->Size;
14719
0
    }
14720
0
    window->Viewport->UpdateWorkRect();
14721
14722
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14723
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14724
0
    if (viewport_rect_changed)
14725
0
        UpdateViewportPlatformMonitor(window->Viewport);
14726
14727
    // Update common viewport flags
14728
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14729
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14730
0
    ImGuiWindowFlags window_flags = window->Flags;
14731
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14732
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14733
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14734
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14735
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14736
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14737
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14738
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14739
14740
    // Not correct to set modal as topmost because:
14741
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14742
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14743
    //if (flags & ImGuiWindowFlags_Modal)
14744
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14745
14746
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14747
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14748
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14749
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14750
0
    if (is_short_lived_floating_window && !is_modal)
14751
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14752
14753
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14754
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14755
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14756
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14757
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14758
14759
    // We can also tell the backend that clearing the platform window won't be necessary,
14760
    // as our window background is filling the viewport and we have disabled BgAlpha.
14761
    // FIXME: Work on support for per-viewport transparency (#2766)
14762
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14763
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14764
14765
0
    window->Viewport->Flags = viewport_flags;
14766
14767
    // Update parent viewport ID
14768
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14769
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14770
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14771
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14772
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14773
0
    else
14774
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14775
0
}
14776
14777
// Called by user at the end of the main loop, after EndFrame()
14778
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14779
void ImGui::UpdatePlatformWindows()
14780
0
{
14781
0
    ImGuiContext& g = *GImGui;
14782
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14783
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14784
0
    g.FrameCountPlatformEnded = g.FrameCount;
14785
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14786
0
        return;
14787
14788
    // Create/resize/destroy platform windows to match each active viewport.
14789
    // Skip the main viewport (index 0), which is always fully handled by the application!
14790
0
    for (int i = 1; i < g.Viewports.Size; i++)
14791
0
    {
14792
0
        ImGuiViewportP* viewport = g.Viewports[i];
14793
14794
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14795
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14796
0
        bool destroy_platform_window = false;
14797
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14798
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14799
0
        if (destroy_platform_window)
14800
0
        {
14801
0
            DestroyPlatformWindow(viewport);
14802
0
            continue;
14803
0
        }
14804
14805
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14806
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14807
0
            continue;
14808
14809
        // Create window
14810
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14811
0
        if (is_new_platform_window)
14812
0
        {
14813
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14814
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14815
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14816
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14817
0
            g.PlatformWindowsCreatedCount++;
14818
0
            viewport->LastNameHash = 0;
14819
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14820
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14821
0
            viewport->PlatformWindowCreated = true;
14822
0
        }
14823
14824
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14825
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14826
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14827
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14828
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14829
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14830
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14831
0
        viewport->LastPlatformPos = viewport->Pos;
14832
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14833
14834
        // Update title bar (if it changed)
14835
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14836
0
        {
14837
0
            const char* title_begin = window_for_title->Name;
14838
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14839
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14840
0
            if (viewport->LastNameHash != title_hash)
14841
0
            {
14842
0
                char title_end_backup_c = *title_end;
14843
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14844
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14845
0
                *title_end = title_end_backup_c;
14846
0
                viewport->LastNameHash = title_hash;
14847
0
            }
14848
0
        }
14849
14850
        // Update alpha (if it changed)
14851
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14852
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14853
0
        viewport->LastAlpha = viewport->Alpha;
14854
14855
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14856
0
        if (g.PlatformIO.Platform_UpdateWindow)
14857
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14858
14859
0
        if (is_new_platform_window)
14860
0
        {
14861
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14862
0
            if (g.FrameCount < 3)
14863
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14864
14865
            // Show window
14866
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14867
14868
            // Even without focus, we assume the window becomes front-most.
14869
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14870
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14871
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14872
0
        }
14873
14874
        // Clear request flags
14875
0
        viewport->ClearRequestFlags();
14876
0
    }
14877
0
}
14878
14879
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14880
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14881
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14882
//
14883
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14884
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14885
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14886
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14887
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14888
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14889
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14890
//
14891
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14892
0
{
14893
    // Skip the main viewport (index 0), which is always fully handled by the application!
14894
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14895
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14896
0
    {
14897
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14898
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14899
0
            continue;
14900
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14901
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14902
0
    }
14903
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14904
0
    {
14905
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14906
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14907
0
            continue;
14908
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14909
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14910
0
    }
14911
0
}
14912
14913
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14914
0
{
14915
0
    ImGuiContext& g = *GImGui;
14916
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14917
0
    {
14918
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14919
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14920
0
            return monitor_n;
14921
0
    }
14922
0
    return -1;
14923
0
}
14924
14925
// Search for the monitor with the largest intersection area with the given rectangle
14926
// We generally try to avoid searching loops but the monitor count should be very small here
14927
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14928
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14929
54.1k
{
14930
54.1k
    ImGuiContext& g = *GImGui;
14931
14932
54.1k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14933
54.1k
    if (monitor_count <= 1)
14934
54.1k
        return monitor_count - 1;
14935
14936
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14937
    // This is necessary for tooltips which always resize down to zero at first.
14938
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14939
0
    int best_monitor_n = -1;
14940
0
    float best_monitor_surface = 0.001f;
14941
14942
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14943
0
    {
14944
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14945
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14946
0
        if (monitor_rect.Contains(rect))
14947
0
            return monitor_n;
14948
0
        ImRect overlapping_rect = rect;
14949
0
        overlapping_rect.ClipWithFull(monitor_rect);
14950
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14951
0
        if (overlapping_surface < best_monitor_surface)
14952
0
            continue;
14953
0
        best_monitor_surface = overlapping_surface;
14954
0
        best_monitor_n = monitor_n;
14955
0
    }
14956
0
    return best_monitor_n;
14957
0
}
14958
14959
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14960
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14961
54.1k
{
14962
54.1k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14963
54.1k
}
14964
14965
// Return value is always != NULL, but don't hold on it across frames.
14966
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14967
0
{
14968
0
    ImGuiContext& g = *GImGui;
14969
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14970
0
    int monitor_idx = viewport->PlatformMonitor;
14971
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14972
0
        return &g.PlatformIO.Monitors[monitor_idx];
14973
0
    return &g.FallbackMonitor;
14974
0
}
14975
14976
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14977
0
{
14978
0
    ImGuiContext& g = *GImGui;
14979
0
    if (viewport->PlatformWindowCreated)
14980
0
    {
14981
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14982
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14983
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14984
0
        if (g.PlatformIO.Platform_DestroyWindow)
14985
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14986
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14987
14988
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14989
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14990
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14991
0
            viewport->PlatformWindowCreated = false;
14992
0
    }
14993
0
    else
14994
0
    {
14995
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14996
0
    }
14997
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14998
0
    viewport->ClearRequestFlags();
14999
0
}
15000
15001
void ImGui::DestroyPlatformWindows()
15002
0
{
15003
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15004
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15005
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15006
    // code to operator a consistent manner.
15007
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15008
    // crashing if it doesn't have data stored.
15009
0
    ImGuiContext& g = *GImGui;
15010
0
    for (ImGuiViewportP* viewport : g.Viewports)
15011
0
        DestroyPlatformWindow(viewport);
15012
0
}
15013
15014
15015
//-----------------------------------------------------------------------------
15016
// [SECTION] DOCKING
15017
//-----------------------------------------------------------------------------
15018
// Docking: Internal Types
15019
// Docking: Forward Declarations
15020
// Docking: ImGuiDockContext
15021
// Docking: ImGuiDockContext Docking/Undocking functions
15022
// Docking: ImGuiDockNode
15023
// Docking: ImGuiDockNode Tree manipulation functions
15024
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15025
// Docking: Builder Functions
15026
// Docking: Begin/End Support Functions (called from Begin/End)
15027
// Docking: Settings
15028
//-----------------------------------------------------------------------------
15029
15030
//-----------------------------------------------------------------------------
15031
// Typical Docking call flow: (root level is generally public API):
15032
//-----------------------------------------------------------------------------
15033
// - NewFrame()                               new dear imgui frame
15034
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15035
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15036
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15037
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15038
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15039
//    | - DockContextProcessDock()            - process one docking request
15040
//    | - DockNodeUpdate()
15041
//    |   - DockNodeUpdateForRootNode()
15042
//    |     - DockNodeUpdateFlagsAndCollapse()
15043
//    |     - DockNodeFindInfo()
15044
//    |   - destroy unused node or tab bar
15045
//    |   - create dock node host window
15046
//    |      - Begin() etc.
15047
//    |   - DockNodeStartMouseMovingWindow()
15048
//    |   - DockNodeTreeUpdatePosSize()
15049
//    |   - DockNodeTreeUpdateSplitter()
15050
//    |   - draw node background
15051
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15052
//    |     - DockNodeAddTabBar()
15053
//    |     - DockNodeUpdateWindowMenu()
15054
//    |     - DockNodeCalcTabBarLayout()
15055
//    |     - BeginTabBarEx()
15056
//    |     - TabItemEx() calls
15057
//    |     - EndTabBar()
15058
//    |   - BeginDockableDragDropTarget()
15059
//    |      - DockNodeUpdate()               - recurse into child nodes...
15060
//-----------------------------------------------------------------------------
15061
// - DockSpace()                              user submit a dockspace into a window
15062
//    | Begin(Child)                          - create a child window
15063
//    | DockNodeUpdate()                      - call main dock node update function
15064
//    | End(Child)
15065
//    | ItemSize()
15066
//-----------------------------------------------------------------------------
15067
// - Begin()
15068
//    | BeginDocked()
15069
//    | BeginDockableDragDropSource()
15070
//    | BeginDockableDragDropTarget()
15071
//    | - DockNodePreviewDockRender()
15072
//-----------------------------------------------------------------------------
15073
// - EndFrame()
15074
//    | DockContextEndFrame()
15075
//-----------------------------------------------------------------------------
15076
15077
//-----------------------------------------------------------------------------
15078
// Docking: Internal Types
15079
//-----------------------------------------------------------------------------
15080
// - ImGuiDockRequestType
15081
// - ImGuiDockRequest
15082
// - ImGuiDockPreviewData
15083
// - ImGuiDockNodeSettings
15084
// - ImGuiDockContext
15085
//-----------------------------------------------------------------------------
15086
15087
enum ImGuiDockRequestType
15088
{
15089
    ImGuiDockRequestType_None = 0,
15090
    ImGuiDockRequestType_Dock,
15091
    ImGuiDockRequestType_Undock,
15092
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15093
};
15094
15095
struct ImGuiDockRequest
15096
{
15097
    ImGuiDockRequestType    Type;
15098
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15099
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15100
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15101
    ImGuiDir                DockSplitDir;
15102
    float                   DockSplitRatio;
15103
    bool                    DockSplitOuter;
15104
    ImGuiWindow*            UndockTargetWindow;
15105
    ImGuiDockNode*          UndockTargetNode;
15106
15107
    ImGuiDockRequest()
15108
0
    {
15109
0
        Type = ImGuiDockRequestType_None;
15110
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15111
0
        DockTargetNode = UndockTargetNode = NULL;
15112
0
        DockSplitDir = ImGuiDir_None;
15113
0
        DockSplitRatio = 0.5f;
15114
0
        DockSplitOuter = false;
15115
0
    }
15116
};
15117
15118
struct ImGuiDockPreviewData
15119
{
15120
    ImGuiDockNode   FutureNode;
15121
    bool            IsDropAllowed;
15122
    bool            IsCenterAvailable;
15123
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15124
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15125
    ImGuiDockNode*  SplitNode;
15126
    ImGuiDir        SplitDir;
15127
    float           SplitRatio;
15128
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15129
15130
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15131
};
15132
15133
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15134
struct ImGuiDockNodeSettings
15135
{
15136
    ImGuiID             ID;
15137
    ImGuiID             ParentNodeId;
15138
    ImGuiID             ParentWindowId;
15139
    ImGuiID             SelectedTabId;
15140
    signed char         SplitAxis;
15141
    char                Depth;
15142
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15143
    ImVec2ih            Pos;
15144
    ImVec2ih            Size;
15145
    ImVec2ih            SizeRef;
15146
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15147
};
15148
15149
//-----------------------------------------------------------------------------
15150
// Docking: Forward Declarations
15151
//-----------------------------------------------------------------------------
15152
15153
namespace ImGui
15154
{
15155
    // ImGuiDockContext
15156
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15157
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15158
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15159
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15160
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15161
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15162
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15163
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15164
15165
    // ImGuiDockNode
15166
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15167
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15168
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15169
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15170
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15171
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15172
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15173
    static void             DockNodeUpdate(ImGuiDockNode* node);
15174
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15175
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15176
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15177
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15178
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15179
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15180
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15181
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15182
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15183
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15184
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15185
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15186
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15187
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15188
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15189
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15190
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15191
15192
    // ImGuiDockNode tree manipulations
15193
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15194
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15195
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15196
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15197
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15198
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15199
15200
    // Settings
15201
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15202
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15203
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15204
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15205
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15206
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15207
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15208
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15209
}
15210
15211
//-----------------------------------------------------------------------------
15212
// Docking: ImGuiDockContext
15213
//-----------------------------------------------------------------------------
15214
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15215
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15216
// At boot time only, we run a simple GC to remove nodes that have no references.
15217
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15218
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15219
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15220
//-----------------------------------------------------------------------------
15221
// - DockContextInitialize()
15222
// - DockContextShutdown()
15223
// - DockContextClearNodes()
15224
// - DockContextRebuildNodes()
15225
// - DockContextNewFrameUpdateUndocking()
15226
// - DockContextNewFrameUpdateDocking()
15227
// - DockContextEndFrame()
15228
// - DockContextFindNodeByID()
15229
// - DockContextBindNodeToWindow()
15230
// - DockContextGenNodeID()
15231
// - DockContextAddNode()
15232
// - DockContextRemoveNode()
15233
// - ImGuiDockContextPruneNodeData
15234
// - DockContextPruneUnusedSettingsNodes()
15235
// - DockContextBuildNodesFromSettings()
15236
// - DockContextBuildAddWindowsToNodes()
15237
//-----------------------------------------------------------------------------
15238
15239
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15240
1
{
15241
1
    ImGuiContext& g = *ctx;
15242
15243
    // Add .ini handle for persistent docking data
15244
1
    ImGuiSettingsHandler ini_handler;
15245
1
    ini_handler.TypeName = "Docking";
15246
1
    ini_handler.TypeHash = ImHashStr("Docking");
15247
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15248
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15249
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15250
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15251
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15252
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15253
1
    g.SettingsHandlers.push_back(ini_handler);
15254
15255
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15256
1
}
15257
15258
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15259
0
{
15260
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15261
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15262
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15263
0
            IM_DELETE(node);
15264
0
}
15265
15266
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15267
0
{
15268
0
    IM_UNUSED(ctx);
15269
0
    IM_ASSERT(ctx == GImGui);
15270
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15271
0
    DockBuilderRemoveNodeChildNodes(root_id);
15272
0
}
15273
15274
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15275
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15276
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15277
0
{
15278
0
    ImGuiContext& g = *ctx;
15279
0
    ImGuiDockContext* dc = &ctx->DockContext;
15280
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15281
0
    SaveIniSettingsToMemory();
15282
0
    ImGuiID root_id = 0; // Rebuild all
15283
0
    DockContextClearNodes(ctx, root_id, false);
15284
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15285
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15286
0
}
15287
15288
// Docking context update function, called by NewFrame()
15289
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15290
54.1k
{
15291
54.1k
    ImGuiContext& g = *ctx;
15292
54.1k
    ImGuiDockContext* dc = &ctx->DockContext;
15293
54.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15294
0
    {
15295
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15296
0
            DockContextClearNodes(ctx, 0, true);
15297
0
        return;
15298
0
    }
15299
15300
    // Setting NoSplit at runtime merges all nodes
15301
54.1k
    if (g.IO.ConfigDockingNoSplit)
15302
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15303
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15304
0
                if (node->IsRootNode() && node->IsSplitNode())
15305
0
                {
15306
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15307
                    //dc->WantFullRebuild = true;
15308
0
                }
15309
15310
    // Process full rebuild
15311
#if 0
15312
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15313
        dc->WantFullRebuild = true;
15314
#endif
15315
54.1k
    if (dc->WantFullRebuild)
15316
0
    {
15317
0
        DockContextRebuildNodes(ctx);
15318
0
        dc->WantFullRebuild = false;
15319
0
    }
15320
15321
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15322
54.1k
    for (ImGuiDockRequest& req : dc->Requests)
15323
0
    {
15324
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15325
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15326
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15327
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15328
0
    }
15329
54.1k
}
15330
15331
// Docking context update function, called by NewFrame()
15332
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15333
54.1k
{
15334
54.1k
    ImGuiContext& g = *ctx;
15335
54.1k
    ImGuiDockContext* dc  = &ctx->DockContext;
15336
54.1k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15337
0
        return;
15338
15339
    // [DEBUG] Store hovered dock node.
15340
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15341
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15342
54.1k
    g.DebugHoveredDockNode = NULL;
15343
54.1k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15344
1.18k
    {
15345
1.18k
        if (hovered_window->DockNodeAsHost)
15346
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15347
1.18k
        else if (hovered_window->RootWindow->DockNode)
15348
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15349
1.18k
    }
15350
15351
    // Process Docking requests
15352
54.1k
    for (ImGuiDockRequest& req : dc->Requests)
15353
0
        if (req.Type == ImGuiDockRequestType_Dock)
15354
0
            DockContextProcessDock(ctx, &req);
15355
54.1k
    dc->Requests.resize(0);
15356
15357
    // Create windows for each automatic docking nodes
15358
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15359
54.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15360
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15361
0
            if (node->IsFloatingNode())
15362
0
                DockNodeUpdate(node);
15363
54.1k
}
15364
15365
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15366
54.1k
{
15367
    // Draw backgrounds of node missing their window
15368
54.1k
    ImGuiContext& g = *ctx;
15369
54.1k
    ImGuiDockContext* dc = &g.DockContext;
15370
54.1k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15371
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15372
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15373
0
            {
15374
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15375
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15376
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15377
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15378
0
            }
15379
54.1k
}
15380
15381
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15382
0
{
15383
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15384
0
}
15385
15386
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15387
0
{
15388
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15389
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15390
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15391
0
    ImGuiID id = 0x0001;
15392
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15393
0
        id++;
15394
0
    return id;
15395
0
}
15396
15397
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15398
0
{
15399
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15400
0
    ImGuiContext& g = *ctx;
15401
0
    if (id == 0)
15402
0
        id = DockContextGenNodeID(ctx);
15403
0
    else
15404
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15405
15406
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15407
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15408
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15409
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15410
0
    return node;
15411
0
}
15412
15413
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15414
0
{
15415
0
    ImGuiContext& g = *ctx;
15416
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15417
15418
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15419
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15420
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15421
0
    IM_ASSERT(node->Windows.Size == 0);
15422
15423
0
    if (node->HostWindow)
15424
0
        node->HostWindow->DockNodeAsHost = NULL;
15425
15426
0
    ImGuiDockNode* parent_node = node->ParentNode;
15427
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15428
0
    if (merge)
15429
0
    {
15430
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15431
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15432
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15433
0
    }
15434
0
    else
15435
0
    {
15436
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15437
0
            if (parent_node->ChildNodes[n] == node)
15438
0
                node->ParentNode->ChildNodes[n] = NULL;
15439
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15440
0
        IM_DELETE(node);
15441
0
    }
15442
0
}
15443
15444
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15445
0
{
15446
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15447
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15448
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15449
0
}
15450
15451
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15452
struct ImGuiDockContextPruneNodeData
15453
{
15454
    int         CountWindows, CountChildWindows, CountChildNodes;
15455
    ImGuiID     RootId;
15456
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15457
};
15458
15459
// Garbage collect unused nodes (run once at init time)
15460
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15461
0
{
15462
0
    ImGuiContext& g = *ctx;
15463
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15464
0
    IM_ASSERT(g.Windows.Size == 0);
15465
15466
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15467
0
    pool.Reserve(dc->NodesSettings.Size);
15468
15469
    // Count child nodes and compute RootID
15470
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15471
0
    {
15472
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15473
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15474
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15475
0
        if (settings->ParentNodeId)
15476
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15477
0
    }
15478
15479
    // Count reference to dock ids from dockspaces
15480
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15481
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15482
0
    {
15483
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15484
0
        if (settings->ParentWindowId != 0)
15485
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15486
0
                if (window_settings->DockId)
15487
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15488
0
                        data->CountChildNodes++;
15489
0
    }
15490
15491
    // Count reference to dock ids from window settings
15492
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15493
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15494
0
        if (ImGuiID dock_id = settings->DockId)
15495
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15496
0
            {
15497
0
                data->CountWindows++;
15498
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15499
0
                    data_root->CountChildWindows++;
15500
0
            }
15501
15502
    // Prune
15503
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15504
0
    {
15505
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15506
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15507
0
        if (data->CountWindows > 1)
15508
0
            continue;
15509
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15510
15511
0
        bool remove = false;
15512
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15513
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15514
0
        remove |= (data_root->CountChildWindows == 0);
15515
0
        if (remove)
15516
0
        {
15517
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15518
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15519
0
            settings->ID = 0;
15520
0
        }
15521
0
    }
15522
0
}
15523
15524
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15525
0
{
15526
    // Build nodes
15527
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15528
0
    {
15529
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15530
0
        if (settings->ID == 0)
15531
0
            continue;
15532
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15533
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15534
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15535
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15536
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15537
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15538
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15539
0
            node->ParentNode->ChildNodes[0] = node;
15540
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15541
0
            node->ParentNode->ChildNodes[1] = node;
15542
0
        node->SelectedTabId = settings->SelectedTabId;
15543
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15544
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15545
15546
        // Bind host window immediately if it already exist (in case of a rebuild)
15547
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15548
0
        char host_window_title[20];
15549
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15550
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15551
0
    }
15552
0
}
15553
15554
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15555
0
{
15556
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15557
0
    ImGuiContext& g = *ctx;
15558
0
    for (ImGuiWindow* window : g.Windows)
15559
0
    {
15560
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15561
0
            continue;
15562
0
        if (window->DockNode != NULL)
15563
0
            continue;
15564
15565
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15566
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15567
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15568
0
            DockNodeAddWindow(node, window, true);
15569
0
    }
15570
0
}
15571
15572
//-----------------------------------------------------------------------------
15573
// Docking: ImGuiDockContext Docking/Undocking functions
15574
//-----------------------------------------------------------------------------
15575
// - DockContextQueueDock()
15576
// - DockContextQueueUndockWindow()
15577
// - DockContextQueueUndockNode()
15578
// - DockContextQueueNotifyRemovedNode()
15579
// - DockContextProcessDock()
15580
// - DockContextProcessUndockWindow()
15581
// - DockContextProcessUndockNode()
15582
// - DockContextCalcDropPosForDocking()
15583
//-----------------------------------------------------------------------------
15584
15585
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15586
0
{
15587
0
    IM_ASSERT(target != payload);
15588
0
    ImGuiDockRequest req;
15589
0
    req.Type = ImGuiDockRequestType_Dock;
15590
0
    req.DockTargetWindow = target;
15591
0
    req.DockTargetNode = target_node;
15592
0
    req.DockPayload = payload;
15593
0
    req.DockSplitDir = split_dir;
15594
0
    req.DockSplitRatio = split_ratio;
15595
0
    req.DockSplitOuter = split_outer;
15596
0
    ctx->DockContext.Requests.push_back(req);
15597
0
}
15598
15599
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15600
0
{
15601
0
    ImGuiDockRequest req;
15602
0
    req.Type = ImGuiDockRequestType_Undock;
15603
0
    req.UndockTargetWindow = window;
15604
0
    ctx->DockContext.Requests.push_back(req);
15605
0
}
15606
15607
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15608
0
{
15609
0
    ImGuiDockRequest req;
15610
0
    req.Type = ImGuiDockRequestType_Undock;
15611
0
    req.UndockTargetNode = node;
15612
0
    ctx->DockContext.Requests.push_back(req);
15613
0
}
15614
15615
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15616
0
{
15617
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15618
0
    for (ImGuiDockRequest& req : dc->Requests)
15619
0
        if (req.DockTargetNode == node)
15620
0
            req.Type = ImGuiDockRequestType_None;
15621
0
}
15622
15623
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15624
0
{
15625
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15626
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15627
15628
0
    ImGuiContext& g = *ctx;
15629
0
    IM_UNUSED(g);
15630
15631
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15632
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15633
0
    ImGuiDockNode* node = req->DockTargetNode;
15634
0
    if (payload_window)
15635
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15636
0
    else
15637
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15638
15639
    // Decide which Tab will be selected at the end of the operation
15640
0
    ImGuiID next_selected_id = 0;
15641
0
    ImGuiDockNode* payload_node = NULL;
15642
0
    if (payload_window)
15643
0
    {
15644
0
        payload_node = payload_window->DockNodeAsHost;
15645
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15646
0
        if (payload_node && payload_node->IsLeafNode())
15647
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15648
0
        if (payload_node == NULL)
15649
0
            next_selected_id = payload_window->TabId;
15650
0
    }
15651
15652
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15653
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15654
0
    if (node)
15655
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15656
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15657
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15658
15659
    // Create new node and add existing window to it
15660
0
    if (node == NULL)
15661
0
    {
15662
0
        node = DockContextAddNode(ctx, 0);
15663
0
        node->Pos = target_window->Pos;
15664
0
        node->Size = target_window->Size;
15665
0
        if (target_window->DockNodeAsHost == NULL)
15666
0
        {
15667
0
            DockNodeAddWindow(node, target_window, true);
15668
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15669
0
            target_window->DockIsActive = true;
15670
0
        }
15671
0
    }
15672
15673
0
    ImGuiDir split_dir = req->DockSplitDir;
15674
0
    if (split_dir != ImGuiDir_None)
15675
0
    {
15676
        // Split into two, one side will be our payload node unless we are dropping a loose window
15677
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15678
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15679
0
        const float split_ratio = req->DockSplitRatio;
15680
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15681
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15682
0
        new_node->HostWindow = node->HostWindow;
15683
0
        node = new_node;
15684
0
    }
15685
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15686
15687
0
    if (node != payload_node)
15688
0
    {
15689
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15690
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15691
0
        {
15692
0
            DockNodeAddTabBar(node);
15693
0
            for (int n = 0; n < node->Windows.Size; n++)
15694
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15695
0
        }
15696
15697
0
        if (payload_node != NULL)
15698
0
        {
15699
            // Transfer full payload node (with 1+ child windows or child nodes)
15700
0
            if (payload_node->IsSplitNode())
15701
0
            {
15702
0
                if (node->Windows.Size > 0)
15703
0
                {
15704
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15705
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15706
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15707
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15708
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15709
0
                    if (visible_node->TabBar)
15710
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15711
0
                    DockNodeMoveWindows(node, visible_node);
15712
0
                    DockNodeMoveWindows(visible_node, node);
15713
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15714
0
                }
15715
0
                if (node->IsCentralNode())
15716
0
                {
15717
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15718
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15719
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15720
0
                    IM_ASSERT(last_focused_node != NULL);
15721
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15722
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15723
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15724
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15725
0
                    last_focused_root_node->CentralNode = last_focused_node;
15726
0
                }
15727
15728
0
                IM_ASSERT(node->Windows.Size == 0);
15729
0
                DockNodeMoveChildNodes(node, payload_node);
15730
0
            }
15731
0
            else
15732
0
            {
15733
0
                const ImGuiID payload_dock_id = payload_node->ID;
15734
0
                DockNodeMoveWindows(node, payload_node);
15735
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15736
0
            }
15737
0
            DockContextRemoveNode(ctx, payload_node, true);
15738
0
        }
15739
0
        else if (payload_window)
15740
0
        {
15741
            // Transfer single window
15742
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15743
0
            node->VisibleWindow = payload_window;
15744
0
            DockNodeAddWindow(node, payload_window, true);
15745
0
            if (payload_dock_id != 0)
15746
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15747
0
        }
15748
0
    }
15749
0
    else
15750
0
    {
15751
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15752
0
        node->WantHiddenTabBarUpdate = true;
15753
0
    }
15754
15755
    // Update selection immediately
15756
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15757
0
        tab_bar->NextSelectedTabId = next_selected_id;
15758
0
    MarkIniSettingsDirty();
15759
0
}
15760
15761
// Problem:
15762
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15763
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15764
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15765
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15766
// Solution:
15767
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15768
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15769
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15770
0
{
15771
0
    if (ref_viewport == NULL)
15772
0
        return size;
15773
15774
0
    ImGuiContext& g = *GImGui;
15775
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
15776
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15777
0
    {
15778
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15779
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
15780
0
    }
15781
0
    return ImMin(size, max_size);
15782
0
}
15783
15784
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15785
0
{
15786
0
    ImGuiContext& g = *ctx;
15787
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15788
0
    if (window->DockNode)
15789
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15790
0
    else
15791
0
        window->DockId = 0;
15792
0
    window->Collapsed = false;
15793
0
    window->DockIsActive = false;
15794
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15795
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15796
15797
0
    MarkIniSettingsDirty();
15798
0
}
15799
15800
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15801
0
{
15802
0
    ImGuiContext& g = *ctx;
15803
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15804
0
    IM_ASSERT(node->IsLeafNode());
15805
0
    IM_ASSERT(node->Windows.Size >= 1);
15806
15807
0
    if (node->IsRootNode() || node->IsCentralNode())
15808
0
    {
15809
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15810
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15811
0
        new_node->Pos = node->Pos;
15812
0
        new_node->Size = node->Size;
15813
0
        new_node->SizeRef = node->SizeRef;
15814
0
        DockNodeMoveWindows(new_node, node);
15815
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15816
0
        node = new_node;
15817
0
    }
15818
0
    else
15819
0
    {
15820
        // Otherwise extract our node and merge our sibling back into the parent node.
15821
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15822
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15823
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15824
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15825
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15826
0
        node->ParentNode = NULL;
15827
0
    }
15828
0
    for (ImGuiWindow* window : node->Windows)
15829
0
    {
15830
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15831
0
        if (window->ParentWindow)
15832
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15833
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15834
0
    }
15835
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15836
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15837
0
    node->WantMouseMove = true;
15838
0
    MarkIniSettingsDirty();
15839
0
}
15840
15841
// This is mostly used for automation.
15842
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15843
0
{
15844
0
    if (target != NULL && target_node == NULL)
15845
0
        target_node = target->DockNode;
15846
15847
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15848
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15849
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15850
0
        split_outer = true;
15851
0
    ImGuiDockPreviewData split_data;
15852
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15853
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15854
0
        return false;
15855
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15856
0
    return true;
15857
0
}
15858
15859
//-----------------------------------------------------------------------------
15860
// Docking: ImGuiDockNode
15861
//-----------------------------------------------------------------------------
15862
// - DockNodeGetTabOrder()
15863
// - DockNodeAddWindow()
15864
// - DockNodeRemoveWindow()
15865
// - DockNodeMoveChildNodes()
15866
// - DockNodeMoveWindows()
15867
// - DockNodeApplyPosSizeToWindows()
15868
// - DockNodeHideHostWindow()
15869
// - ImGuiDockNodeFindInfoResults
15870
// - DockNodeFindInfo()
15871
// - DockNodeFindWindowByID()
15872
// - DockNodeUpdateFlagsAndCollapse()
15873
// - DockNodeUpdateHasCentralNodeFlag()
15874
// - DockNodeUpdateVisibleFlag()
15875
// - DockNodeStartMouseMovingWindow()
15876
// - DockNodeUpdate()
15877
// - DockNodeUpdateWindowMenu()
15878
// - DockNodeBeginAmendTabBar()
15879
// - DockNodeEndAmendTabBar()
15880
// - DockNodeUpdateTabBar()
15881
// - DockNodeAddTabBar()
15882
// - DockNodeRemoveTabBar()
15883
// - DockNodeIsDropAllowedOne()
15884
// - DockNodeIsDropAllowed()
15885
// - DockNodeCalcTabBarLayout()
15886
// - DockNodeCalcSplitRects()
15887
// - DockNodeCalcDropRectsAndTestMousePos()
15888
// - DockNodePreviewDockSetup()
15889
// - DockNodePreviewDockRender()
15890
//-----------------------------------------------------------------------------
15891
15892
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15893
0
{
15894
0
    ID = id;
15895
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15896
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15897
0
    TabBar = NULL;
15898
0
    SplitAxis = ImGuiAxis_None;
15899
15900
0
    State = ImGuiDockNodeState_Unknown;
15901
0
    LastBgColor = IM_COL32_WHITE;
15902
0
    HostWindow = VisibleWindow = NULL;
15903
0
    CentralNode = OnlyNodeWithWindows = NULL;
15904
0
    CountNodeWithWindows = 0;
15905
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15906
0
    LastFocusedNodeId = 0;
15907
0
    SelectedTabId = 0;
15908
0
    WantCloseTabId = 0;
15909
0
    RefViewportId = 0;
15910
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15911
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15912
0
    IsVisible = true;
15913
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15914
0
    IsBgDrawnThisFrame = false;
15915
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15916
0
}
15917
15918
ImGuiDockNode::~ImGuiDockNode()
15919
0
{
15920
0
    IM_DELETE(TabBar);
15921
0
    TabBar = NULL;
15922
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15923
0
}
15924
15925
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15926
0
{
15927
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15928
0
    if (tab_bar == NULL)
15929
0
        return -1;
15930
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15931
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15932
0
}
15933
15934
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15935
0
{
15936
0
    window->Hidden = true;
15937
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15938
0
}
15939
15940
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15941
0
{
15942
0
    ImGuiContext& g = *GImGui; (void)g;
15943
0
    if (window->DockNode)
15944
0
    {
15945
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15946
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15947
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15948
0
    }
15949
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15950
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15951
15952
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15953
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15954
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15955
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15956
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15957
15958
0
    node->Windows.push_back(window);
15959
0
    node->WantHiddenTabBarUpdate = true;
15960
0
    window->DockNode = node;
15961
0
    window->DockId = node->ID;
15962
0
    window->DockIsActive = (node->Windows.Size > 1);
15963
0
    window->DockTabWantClose = false;
15964
15965
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15966
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15967
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15968
0
    {
15969
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15970
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15971
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15972
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15973
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15974
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15975
0
    }
15976
15977
    // Add to tab bar if requested
15978
0
    if (add_to_tab_bar)
15979
0
    {
15980
0
        if (node->TabBar == NULL)
15981
0
        {
15982
0
            DockNodeAddTabBar(node);
15983
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15984
15985
            // Add existing windows
15986
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15987
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15988
0
        }
15989
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15990
0
    }
15991
15992
0
    DockNodeUpdateVisibleFlag(node);
15993
15994
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15995
0
    if (node->HostWindow)
15996
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15997
0
}
15998
15999
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16000
0
{
16001
0
    ImGuiContext& g = *GImGui;
16002
0
    IM_ASSERT(window->DockNode == node);
16003
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16004
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16005
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16006
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16007
16008
0
    window->DockNode = NULL;
16009
0
    window->DockIsActive = window->DockTabWantClose = false;
16010
0
    window->DockId = save_dock_id;
16011
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16012
0
    if (window->ParentWindow)
16013
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16014
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16015
16016
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16017
0
    {
16018
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16019
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16020
0
        window->Viewport = NULL;
16021
0
        window->ViewportId = 0;
16022
0
        window->ViewportOwned = false;
16023
0
        window->Hidden = true;
16024
0
    }
16025
16026
    // Remove window
16027
0
    bool erased = false;
16028
0
    for (int n = 0; n < node->Windows.Size; n++)
16029
0
        if (node->Windows[n] == window)
16030
0
        {
16031
0
            node->Windows.erase(node->Windows.Data + n);
16032
0
            erased = true;
16033
0
            break;
16034
0
        }
16035
0
    if (!erased)
16036
0
        IM_ASSERT(erased);
16037
0
    if (node->VisibleWindow == window)
16038
0
        node->VisibleWindow = NULL;
16039
16040
    // Remove tab and possibly tab bar
16041
0
    node->WantHiddenTabBarUpdate = true;
16042
0
    if (node->TabBar)
16043
0
    {
16044
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16045
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16046
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16047
0
            DockNodeRemoveTabBar(node);
16048
0
    }
16049
16050
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16051
0
    {
16052
        // Automatic dock node delete themselves if they are not holding at least one tab
16053
0
        DockContextRemoveNode(&g, node, true);
16054
0
        return;
16055
0
    }
16056
16057
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16058
0
    {
16059
0
        ImGuiWindow* remaining_window = node->Windows[0];
16060
        // Note: we used to transport viewport ownership here.
16061
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16062
0
    }
16063
16064
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16065
0
    DockNodeUpdateVisibleFlag(node);
16066
0
}
16067
16068
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16069
0
{
16070
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16071
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16072
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16073
0
    if (dst_node->ChildNodes[0])
16074
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16075
0
    if (dst_node->ChildNodes[1])
16076
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16077
0
    dst_node->SplitAxis = src_node->SplitAxis;
16078
0
    dst_node->SizeRef = src_node->SizeRef;
16079
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16080
0
}
16081
16082
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16083
0
{
16084
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16085
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16086
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16087
0
    if (src_tab_bar != NULL)
16088
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16089
16090
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16091
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16092
0
    if (move_tab_bar)
16093
0
    {
16094
0
        dst_node->TabBar = src_node->TabBar;
16095
0
        src_node->TabBar = NULL;
16096
0
    }
16097
16098
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16099
0
    for (ImGuiWindow* window : src_node->Windows)
16100
0
    {
16101
0
        window->DockNode = NULL;
16102
0
        window->DockIsActive = false;
16103
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16104
0
    }
16105
0
    src_node->Windows.clear();
16106
16107
0
    if (!move_tab_bar && src_node->TabBar)
16108
0
    {
16109
0
        if (dst_node->TabBar)
16110
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16111
0
        DockNodeRemoveTabBar(src_node);
16112
0
    }
16113
0
}
16114
16115
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16116
0
{
16117
0
    for (ImGuiWindow* window : node->Windows)
16118
0
    {
16119
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16120
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16121
0
    }
16122
0
}
16123
16124
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16125
0
{
16126
0
    if (node->HostWindow)
16127
0
    {
16128
0
        if (node->HostWindow->DockNodeAsHost == node)
16129
0
            node->HostWindow->DockNodeAsHost = NULL;
16130
0
        node->HostWindow = NULL;
16131
0
    }
16132
16133
0
    if (node->Windows.Size == 1)
16134
0
    {
16135
0
        node->VisibleWindow = node->Windows[0];
16136
0
        node->Windows[0]->DockIsActive = false;
16137
0
    }
16138
16139
0
    if (node->TabBar)
16140
0
        DockNodeRemoveTabBar(node);
16141
0
}
16142
16143
// Search function called once by root node in DockNodeUpdate()
16144
struct ImGuiDockNodeTreeInfo
16145
{
16146
    ImGuiDockNode*      CentralNode;
16147
    ImGuiDockNode*      FirstNodeWithWindows;
16148
    int                 CountNodesWithWindows;
16149
    //ImGuiWindowClass  WindowClassForMerges;
16150
16151
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16152
};
16153
16154
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16155
0
{
16156
0
    if (node->Windows.Size > 0)
16157
0
    {
16158
0
        if (info->FirstNodeWithWindows == NULL)
16159
0
            info->FirstNodeWithWindows = node;
16160
0
        info->CountNodesWithWindows++;
16161
0
    }
16162
0
    if (node->IsCentralNode())
16163
0
    {
16164
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16165
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16166
0
        info->CentralNode = node;
16167
0
    }
16168
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16169
0
        return;
16170
0
    if (node->ChildNodes[0])
16171
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16172
0
    if (node->ChildNodes[1])
16173
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16174
0
}
16175
16176
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16177
0
{
16178
0
    IM_ASSERT(id != 0);
16179
0
    for (ImGuiWindow* window : node->Windows)
16180
0
        if (window->ID == id)
16181
0
            return window;
16182
0
    return NULL;
16183
0
}
16184
16185
// - Remove inactive windows/nodes.
16186
// - Update visibility flag.
16187
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16188
0
{
16189
0
    ImGuiContext& g = *GImGui;
16190
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16191
16192
    // Inherit most flags
16193
0
    if (node->ParentNode)
16194
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16195
16196
    // Recurse into children
16197
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16198
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16199
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16200
0
    node->HasCentralNodeChild = false;
16201
0
    if (node->ChildNodes[0])
16202
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16203
0
    if (node->ChildNodes[1])
16204
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16205
16206
    // Remove inactive windows, collapse nodes
16207
    // Merge node flags overrides stored in windows
16208
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16209
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16210
0
    {
16211
0
        ImGuiWindow* window = node->Windows[window_n];
16212
0
        IM_ASSERT(window->DockNode == node);
16213
16214
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16215
0
        bool remove = false;
16216
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16217
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16218
0
        remove |= (window->DockTabWantClose);
16219
0
        if (remove)
16220
0
        {
16221
0
            window->DockTabWantClose = false;
16222
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16223
0
            {
16224
0
                DockNodeHideHostWindow(node);
16225
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16226
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16227
0
                return;
16228
0
            }
16229
0
            DockNodeRemoveWindow(node, window, node->ID);
16230
0
            window_n--;
16231
0
            continue;
16232
0
        }
16233
16234
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16235
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16236
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16237
0
    }
16238
0
    node->UpdateMergedFlags();
16239
16240
    // Auto-hide tab bar option
16241
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16242
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16243
0
        node->WantHiddenTabBarToggle = true;
16244
0
    node->WantHiddenTabBarUpdate = false;
16245
16246
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16247
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16248
0
        node->WantHiddenTabBarToggle = false;
16249
16250
    // Apply toggles at a single point of the frame (here!)
16251
0
    if (node->Windows.Size > 1)
16252
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16253
0
    else if (node->WantHiddenTabBarToggle)
16254
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16255
0
    node->WantHiddenTabBarToggle = false;
16256
16257
0
    DockNodeUpdateVisibleFlag(node);
16258
0
}
16259
16260
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16261
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16262
0
{
16263
0
    node->HasCentralNodeChild = false;
16264
0
    if (node->ChildNodes[0])
16265
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16266
0
    if (node->ChildNodes[1])
16267
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16268
0
    if (node->IsRootNode())
16269
0
    {
16270
0
        ImGuiDockNode* mark_node = node->CentralNode;
16271
0
        while (mark_node)
16272
0
        {
16273
0
            mark_node->HasCentralNodeChild = true;
16274
0
            mark_node = mark_node->ParentNode;
16275
0
        }
16276
0
    }
16277
0
}
16278
16279
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16280
0
{
16281
    // Update visibility flag
16282
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16283
0
    is_visible |= (node->Windows.Size > 0);
16284
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16285
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16286
0
    node->IsVisible = is_visible;
16287
0
}
16288
16289
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16290
0
{
16291
0
    ImGuiContext& g = *GImGui;
16292
0
    IM_ASSERT(node->WantMouseMove == true);
16293
0
    StartMouseMovingWindow(window);
16294
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16295
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16296
0
    node->WantMouseMove = false;
16297
0
}
16298
16299
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16300
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16301
0
{
16302
0
    DockNodeUpdateFlagsAndCollapse(node);
16303
16304
    // - Setup central node pointers
16305
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16306
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16307
0
    ImGuiDockNodeTreeInfo info;
16308
0
    DockNodeFindInfo(node, &info);
16309
0
    node->CentralNode = info.CentralNode;
16310
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16311
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16312
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16313
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16314
16315
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16316
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16317
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16318
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16319
0
    {
16320
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16321
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16322
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16323
0
            {
16324
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16325
0
                break;
16326
0
            }
16327
0
    }
16328
16329
0
    ImGuiDockNode* mark_node = node->CentralNode;
16330
0
    while (mark_node)
16331
0
    {
16332
0
        mark_node->HasCentralNodeChild = true;
16333
0
        mark_node = mark_node->ParentNode;
16334
0
    }
16335
0
}
16336
16337
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16338
0
{
16339
    // Remove ourselves from any previous different host window
16340
    // This can happen if a user mistakenly does (see #4295 for details):
16341
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16342
    //  - N+1: NewFrame()                   // will create floating host window for that node
16343
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16344
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16345
0
        node->HostWindow->DockNodeAsHost = NULL;
16346
16347
0
    host_window->DockNodeAsHost = node;
16348
0
    node->HostWindow = host_window;
16349
0
}
16350
16351
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16352
0
{
16353
0
    ImGuiContext& g = *GImGui;
16354
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16355
0
    node->LastFrameAlive = g.FrameCount;
16356
0
    node->IsBgDrawnThisFrame = false;
16357
16358
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16359
0
    if (node->IsRootNode())
16360
0
        DockNodeUpdateForRootNode(node);
16361
16362
    // Remove tab bar if not needed
16363
0
    if (node->TabBar && node->IsNoTabBar())
16364
0
        DockNodeRemoveTabBar(node);
16365
16366
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16367
0
    bool want_to_hide_host_window = false;
16368
0
    if (node->IsFloatingNode())
16369
0
    {
16370
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16371
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16372
0
                want_to_hide_host_window = true;
16373
0
        if (node->CountNodeWithWindows == 0)
16374
0
            want_to_hide_host_window = true;
16375
0
    }
16376
0
    if (want_to_hide_host_window)
16377
0
    {
16378
0
        if (node->Windows.Size == 1)
16379
0
        {
16380
            // Floating window pos/size is authoritative
16381
0
            ImGuiWindow* single_window = node->Windows[0];
16382
0
            node->Pos = single_window->Pos;
16383
0
            node->Size = single_window->SizeFull;
16384
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16385
16386
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16387
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16388
0
                FocusWindow(single_window);
16389
0
            if (node->HostWindow)
16390
0
            {
16391
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16392
0
                single_window->Viewport = node->HostWindow->Viewport;
16393
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16394
0
                if (node->HostWindow->ViewportOwned)
16395
0
                {
16396
0
                    single_window->Viewport->ID = single_window->ID;
16397
0
                    single_window->Viewport->Window = single_window;
16398
0
                    single_window->ViewportOwned = true;
16399
0
                }
16400
0
            }
16401
0
            node->RefViewportId = single_window->ViewportId;
16402
0
        }
16403
16404
0
        DockNodeHideHostWindow(node);
16405
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16406
0
        node->WantCloseAll = false;
16407
0
        node->WantCloseTabId = 0;
16408
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16409
0
        node->LastFrameActive = g.FrameCount;
16410
16411
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16412
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16413
0
        return;
16414
0
    }
16415
16416
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16417
    // while the expected visible window is resizing itself.
16418
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16419
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16420
    //   N+0: Begin(): window created (with no known size), node is created
16421
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16422
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16423
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16424
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16425
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16426
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16427
0
    {
16428
0
        IM_ASSERT(node->Windows.Size > 0);
16429
0
        ImGuiWindow* ref_window = NULL;
16430
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16431
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16432
0
        if (ref_window == NULL)
16433
0
            ref_window = node->Windows[0];
16434
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16435
0
        {
16436
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16437
0
            return;
16438
0
        }
16439
0
    }
16440
16441
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16442
16443
    // Decide if the node will have a close button and a window menu button
16444
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16445
0
    node->HasCloseButton = false;
16446
0
    for (ImGuiWindow* window : node->Windows)
16447
0
    {
16448
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16449
0
        node->HasCloseButton |= window->HasCloseButton;
16450
0
        window->DockIsActive = (node->Windows.Size > 1);
16451
0
    }
16452
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16453
0
        node->HasCloseButton = false;
16454
16455
    // Bind or create host window
16456
0
    ImGuiWindow* host_window = NULL;
16457
0
    bool beginned_into_host_window = false;
16458
0
    if (node->IsDockSpace())
16459
0
    {
16460
        // [Explicit root dockspace node]
16461
0
        IM_ASSERT(node->HostWindow);
16462
0
        host_window = node->HostWindow;
16463
0
    }
16464
0
    else
16465
0
    {
16466
        // [Automatic root or child nodes]
16467
0
        if (node->IsRootNode() && node->IsVisible)
16468
0
        {
16469
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16470
16471
            // Sync Pos
16472
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16473
0
                SetNextWindowPos(ref_window->Pos);
16474
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16475
0
                SetNextWindowPos(node->Pos);
16476
16477
            // Sync Size
16478
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16479
0
                SetNextWindowSize(ref_window->SizeFull);
16480
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16481
0
                SetNextWindowSize(node->Size);
16482
16483
            // Sync Collapsed
16484
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16485
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16486
16487
            // Sync Viewport
16488
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16489
0
                SetNextWindowViewport(ref_window->ViewportId);
16490
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16491
0
                SetNextWindowViewport(node->RefViewportId);
16492
16493
0
            SetNextWindowClass(&node->WindowClass);
16494
16495
            // Begin into the host window
16496
0
            char window_label[20];
16497
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16498
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16499
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16500
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16501
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16502
16503
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16504
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16505
0
            Begin(window_label, NULL, window_flags);
16506
0
            PopStyleVar();
16507
0
            beginned_into_host_window = true;
16508
16509
0
            host_window = g.CurrentWindow;
16510
0
            DockNodeSetupHostWindow(node, host_window);
16511
0
            host_window->DC.CursorPos = host_window->Pos;
16512
0
            node->Pos = host_window->Pos;
16513
0
            node->Size = host_window->Size;
16514
16515
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16516
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16517
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16518
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16519
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16520
            // after the dock host window, losing their top-most status.
16521
0
            if (node->HostWindow->Appearing)
16522
0
                BringWindowToDisplayFront(node->HostWindow);
16523
16524
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16525
0
        }
16526
0
        else if (node->ParentNode)
16527
0
        {
16528
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16529
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16530
0
        }
16531
0
        if (node->WantMouseMove && node->HostWindow)
16532
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16533
0
    }
16534
0
    node->RefViewportId = 0; // Clear when we have a host window
16535
16536
    // Update focused node (the one whose title bar is highlight) within a node tree
16537
0
    if (node->IsSplitNode())
16538
0
        IM_ASSERT(node->TabBar == NULL);
16539
0
    if (node->IsRootNode())
16540
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16541
0
            while (p_window != NULL && p_window->DockNode != NULL)
16542
0
            {
16543
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16544
0
                if (p_node == node)
16545
0
                {
16546
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16547
0
                    break;
16548
0
                }
16549
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16550
0
            }
16551
16552
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16553
0
    ImGuiDockNode* central_node = node->CentralNode;
16554
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16555
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16556
0
    if (central_node_hole)
16557
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16558
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16559
0
                central_node_hole_register_hit_test_hole = false;
16560
0
    if (central_node_hole_register_hit_test_hole)
16561
0
    {
16562
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16563
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16564
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16565
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16566
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16567
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16568
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16569
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16570
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16571
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16572
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16573
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16574
0
        if (central_node_hole && !hole_rect.IsInverted())
16575
0
        {
16576
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16577
0
            if (host_window->ParentWindow)
16578
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16579
0
        }
16580
0
    }
16581
16582
    // Update position/size, process and draw resizing splitters
16583
0
    if (node->IsRootNode() && host_window)
16584
0
    {
16585
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16586
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
16587
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
16588
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
16589
0
        DockNodeTreeUpdateSplitter(node);
16590
0
        PopStyleColor(3);
16591
0
    }
16592
16593
    // Draw empty node background (currently can only be the Central Node)
16594
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16595
0
    {
16596
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16597
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16598
0
        if (node->LastBgColor != 0)
16599
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16600
0
        node->IsBgDrawnThisFrame = true;
16601
0
    }
16602
16603
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16604
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16605
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16606
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16607
0
    if (render_dockspace_bg && node->IsVisible)
16608
0
    {
16609
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16610
0
        if (central_node_hole)
16611
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16612
0
        else
16613
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16614
0
    }
16615
16616
    // Draw and populate Tab Bar
16617
0
    if (host_window)
16618
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16619
0
    if (host_window && node->Windows.Size > 0)
16620
0
    {
16621
0
        DockNodeUpdateTabBar(node, host_window);
16622
0
    }
16623
0
    else
16624
0
    {
16625
0
        node->WantCloseAll = false;
16626
0
        node->WantCloseTabId = 0;
16627
0
        node->IsFocused = false;
16628
0
    }
16629
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16630
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16631
0
    else if (node->Windows.Size > 0)
16632
0
        node->SelectedTabId = node->Windows[0]->TabId;
16633
16634
    // Draw payload drop target
16635
0
    if (host_window && node->IsVisible)
16636
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16637
0
            BeginDockableDragDropTarget(host_window);
16638
16639
    // We update this after DockNodeUpdateTabBar()
16640
0
    node->LastFrameActive = g.FrameCount;
16641
16642
    // Recurse into children
16643
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16644
0
    if (host_window)
16645
0
    {
16646
0
        if (node->ChildNodes[0])
16647
0
            DockNodeUpdate(node->ChildNodes[0]);
16648
0
        if (node->ChildNodes[1])
16649
0
            DockNodeUpdate(node->ChildNodes[1]);
16650
16651
        // Render outer borders last (after the tab bar)
16652
0
        if (node->IsRootNode())
16653
0
            RenderWindowOuterBorders(host_window);
16654
0
    }
16655
16656
    // End host window
16657
0
    if (beginned_into_host_window) //-V1020
16658
0
        End();
16659
0
}
16660
16661
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16662
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16663
0
{
16664
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16665
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16666
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16667
0
        return d;
16668
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16669
0
}
16670
16671
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16672
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16673
// Custom overrides may want to decorate, group, sort entries.
16674
// Please note those are internal structures: if you copy this expect occasional breakage.
16675
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16676
0
{
16677
0
    IM_UNUSED(ctx);
16678
0
    if (tab_bar->Tabs.Size == 1)
16679
0
    {
16680
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16681
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16682
0
            node->WantHiddenTabBarToggle = true;
16683
0
    }
16684
0
    else
16685
0
    {
16686
        // Display a selectable list of windows in this docking node
16687
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16688
0
        {
16689
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16690
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16691
0
                continue;
16692
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16693
0
                TabBarQueueFocus(tab_bar, tab);
16694
0
            SameLine();
16695
0
            Text("   ");
16696
0
        }
16697
0
    }
16698
0
}
16699
16700
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16701
0
{
16702
    // Try to position the menu so it is more likely to stays within the same viewport
16703
0
    ImGuiContext& g = *GImGui;
16704
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16705
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16706
0
    else
16707
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16708
0
    if (BeginPopup("#WindowMenu"))
16709
0
    {
16710
0
        node->IsFocused = true;
16711
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16712
0
        EndPopup();
16713
0
    }
16714
0
}
16715
16716
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16717
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16718
0
{
16719
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16720
0
        return false;
16721
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16722
0
        return false;
16723
0
    Begin(node->HostWindow->Name);
16724
0
    PushOverrideID(node->ID);
16725
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
16726
0
    IM_UNUSED(ret);
16727
0
    IM_ASSERT(ret);
16728
0
    return true;
16729
0
}
16730
16731
void ImGui::DockNodeEndAmendTabBar()
16732
0
{
16733
0
    EndTabBar();
16734
0
    PopID();
16735
0
    End();
16736
0
}
16737
16738
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16739
0
{
16740
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16741
0
    ImGuiContext& g = *GImGui;
16742
0
    if (g.NavWindowingTarget)
16743
0
        return (g.NavWindowingTarget->DockNode == node);
16744
16745
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16746
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16747
0
    {
16748
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16749
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16750
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16751
0
            parent_window = parent_window->ParentWindow->RootWindow;
16752
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16753
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16754
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16755
0
                return true;
16756
0
    }
16757
0
    return false;
16758
0
}
16759
16760
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16761
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16762
0
{
16763
0
    ImGuiContext& g = *GImGui;
16764
0
    ImGuiStyle& style = g.Style;
16765
16766
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16767
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16768
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16769
0
    node->WantCloseAll = false;
16770
0
    node->WantCloseTabId = 0;
16771
16772
    // Decide if we should use a focused title bar color
16773
0
    bool is_focused = false;
16774
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16775
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16776
0
        is_focused = true;
16777
16778
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16779
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16780
0
    {
16781
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16782
0
        node->IsFocused = is_focused;
16783
0
        if (is_focused)
16784
0
            node->LastFrameFocused = g.FrameCount;
16785
0
        if (node->VisibleWindow)
16786
0
        {
16787
            // Notify root of visible window (used to display title in OS task bar)
16788
0
            if (is_focused || root_node->VisibleWindow == NULL)
16789
0
                root_node->VisibleWindow = node->VisibleWindow;
16790
0
            if (node->TabBar)
16791
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16792
0
        }
16793
0
        return;
16794
0
    }
16795
16796
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16797
0
    bool backup_skip_item = host_window->SkipItems;
16798
0
    if (!node->IsDockSpace())
16799
0
    {
16800
0
        host_window->SkipItems = false;
16801
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16802
0
    }
16803
16804
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16805
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16806
    // as docked windows themselves will override the stack with their own root ID.
16807
0
    PushOverrideID(node->ID);
16808
0
    ImGuiTabBar* tab_bar = node->TabBar;
16809
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16810
0
    if (tab_bar == NULL)
16811
0
    {
16812
0
        DockNodeAddTabBar(node);
16813
0
        tab_bar = node->TabBar;
16814
0
    }
16815
16816
0
    ImGuiID focus_tab_id = 0;
16817
0
    node->IsFocused = is_focused;
16818
16819
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16820
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16821
16822
    // In a dock node, the Collapse Button turns into the Window Menu button.
16823
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16824
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16825
0
    {
16826
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16827
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16828
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16829
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16830
0
        is_focused |= node->IsFocused;
16831
0
    }
16832
16833
    // Layout
16834
0
    ImRect title_bar_rect, tab_bar_rect;
16835
0
    ImVec2 window_menu_button_pos;
16836
0
    ImVec2 close_button_pos;
16837
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16838
16839
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16840
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16841
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16842
0
    {
16843
0
        ImGuiWindow* window = node->Windows[window_n];
16844
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16845
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16846
0
    }
16847
16848
    // Title bar
16849
0
    if (is_focused)
16850
0
        node->LastFrameFocused = g.FrameCount;
16851
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16852
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
16853
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16854
16855
    // Docking/Collapse button
16856
0
    if (has_window_menu_button)
16857
0
    {
16858
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16859
0
            OpenPopup("#WindowMenu");
16860
0
        if (IsItemActive())
16861
0
            focus_tab_id = tab_bar->SelectedTabId;
16862
0
    }
16863
16864
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16865
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16866
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16867
0
    {
16868
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16869
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16870
0
        tabs_unsorted_start = tab_n;
16871
0
    }
16872
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16873
0
    {
16874
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16875
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16876
0
        {
16877
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16878
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
16879
0
        }
16880
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
16881
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16882
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16883
0
    }
16884
16885
    // Apply NavWindow focus back to the tab bar
16886
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16887
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16888
16889
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16890
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16891
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16892
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16893
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16894
16895
    // Begin tab bar
16896
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16897
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
16898
0
    if (!host_window->Collapsed && is_focused)
16899
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16900
0
    tab_bar->ID = GetID("#TabBar");
16901
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
16902
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
16903
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
16904
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16905
16906
    // Backup style colors
16907
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16908
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16909
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16910
16911
    // Submit actual tabs
16912
0
    node->VisibleWindow = NULL;
16913
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16914
0
    {
16915
0
        ImGuiWindow* window = node->Windows[window_n];
16916
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16917
0
            continue;
16918
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16919
0
        {
16920
0
            ImGuiTabItemFlags tab_item_flags = 0;
16921
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16922
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16923
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16924
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16925
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16926
16927
            // Apply stored style overrides for the window
16928
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16929
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16930
16931
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16932
0
            bool tab_open = true;
16933
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16934
0
            if (!tab_open)
16935
0
                node->WantCloseTabId = window->TabId;
16936
0
            if (tab_bar->VisibleTabId == window->TabId)
16937
0
                node->VisibleWindow = window;
16938
16939
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16940
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16941
0
            window->DockTabItemRect = g.LastItemData.Rect;
16942
16943
            // Update navigation ID on menu layer
16944
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16945
0
                host_window->NavLastIds[1] = window->TabId;
16946
0
        }
16947
0
    }
16948
16949
    // Restore style colors
16950
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16951
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16952
16953
    // Notify root of visible window (used to display title in OS task bar)
16954
0
    if (node->VisibleWindow)
16955
0
        if (is_focused || root_node->VisibleWindow == NULL)
16956
0
            root_node->VisibleWindow = node->VisibleWindow;
16957
16958
    // Close button (after VisibleWindow was updated)
16959
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16960
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16961
0
    const bool close_button_is_visible = node->HasCloseButton;
16962
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16963
0
    if (close_button_is_visible)
16964
0
    {
16965
0
        if (!close_button_is_enabled)
16966
0
        {
16967
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16968
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16969
0
        }
16970
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16971
0
        {
16972
0
            node->WantCloseAll = true;
16973
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16974
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16975
0
        }
16976
        //if (IsItemActive())
16977
        //    focus_tab_id = tab_bar->SelectedTabId;
16978
0
        if (!close_button_is_enabled)
16979
0
        {
16980
0
            PopStyleColor();
16981
0
            PopItemFlag();
16982
0
        }
16983
0
    }
16984
16985
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16986
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
16987
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16988
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16989
0
    {
16990
        // AllowItem mode required for appending into dock node tab bar,
16991
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16992
0
        bool held;
16993
0
        KeepAliveID(title_bar_id);
16994
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
16995
0
        if (g.HoveredId == title_bar_id)
16996
0
        {
16997
0
            g.LastItemData.ID = title_bar_id;
16998
0
        }
16999
0
        if (held)
17000
0
        {
17001
0
            if (IsMouseClicked(0))
17002
0
                focus_tab_id = tab_bar->SelectedTabId;
17003
17004
            // Forward moving request to selected window
17005
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17006
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
17007
0
        }
17008
0
    }
17009
17010
    // Forward focus from host node to selected window
17011
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17012
    //    focus_tab_id = tab_bar->SelectedTabId;
17013
17014
    // When clicked on a tab we requested focus to the docked child
17015
    // This overrides the value set by "forward focus from host node to selected window".
17016
0
    if (tab_bar->NextSelectedTabId)
17017
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17018
17019
    // Apply navigation focus
17020
0
    if (focus_tab_id != 0)
17021
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17022
0
            if (tab->Window)
17023
0
            {
17024
0
                FocusWindow(tab->Window);
17025
0
                NavInitWindow(tab->Window, false);
17026
0
            }
17027
17028
0
    EndTabBar();
17029
0
    PopID();
17030
17031
    // Restore SkipItems flag
17032
0
    if (!node->IsDockSpace())
17033
0
    {
17034
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17035
0
        host_window->SkipItems = backup_skip_item;
17036
0
    }
17037
0
}
17038
17039
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17040
0
{
17041
0
    IM_ASSERT(node->TabBar == NULL);
17042
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17043
0
}
17044
17045
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17046
0
{
17047
0
    if (node->TabBar == NULL)
17048
0
        return;
17049
0
    IM_DELETE(node->TabBar);
17050
0
    node->TabBar = NULL;
17051
0
}
17052
17053
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17054
0
{
17055
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17056
0
        return false;
17057
17058
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17059
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17060
0
    if (host_class->ClassId != payload_class->ClassId)
17061
0
    {
17062
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17063
0
            return true;
17064
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17065
0
            return true;
17066
0
        return false;
17067
0
    }
17068
17069
    // Prevent docking any window created above a popup
17070
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17071
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17072
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17073
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17074
0
    ImGuiContext& g = *GImGui;
17075
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17076
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17077
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17078
0
                return false;
17079
17080
0
    return true;
17081
0
}
17082
17083
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17084
0
{
17085
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17086
0
        return true;
17087
17088
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17089
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17090
0
    {
17091
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17092
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17093
0
            return true;
17094
0
    }
17095
0
    return false;
17096
0
}
17097
17098
// window menu button == collapse button when not in a dock node.
17099
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17100
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17101
0
{
17102
0
    ImGuiContext& g = *GImGui;
17103
0
    ImGuiStyle& style = g.Style;
17104
17105
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17106
0
    if (out_title_rect) { *out_title_rect = r; }
17107
17108
0
    r.Min.x += style.WindowBorderSize;
17109
0
    r.Max.x -= style.WindowBorderSize;
17110
17111
0
    float button_sz = g.FontSize;
17112
0
    r.Min.x += style.FramePadding.x;
17113
0
    r.Max.x -= style.FramePadding.x;
17114
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17115
0
    if (node->HasCloseButton)
17116
0
    {
17117
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17118
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17119
0
    }
17120
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17121
0
    {
17122
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17123
0
    }
17124
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17125
0
    {
17126
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17127
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17128
0
    }
17129
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17130
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17131
0
}
17132
17133
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17134
0
{
17135
0
    ImGuiContext& g = *GImGui;
17136
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17137
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17138
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17139
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17140
17141
    // Distribute size on given axis (with a desired size or equally)
17142
0
    const float w_avail = size_old[axis] - dock_spacing;
17143
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17144
0
    {
17145
0
        size_new[axis] = size_new_desired[axis];
17146
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17147
0
    }
17148
0
    else
17149
0
    {
17150
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17151
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17152
0
    }
17153
17154
    // Position each node
17155
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17156
0
    {
17157
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17158
0
    }
17159
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17160
0
    {
17161
0
        pos_new[axis] = pos_old[axis];
17162
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17163
0
    }
17164
0
}
17165
17166
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17167
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17168
0
{
17169
0
    ImGuiContext& g = *GImGui;
17170
17171
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17172
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17173
0
    float hs_w; // Half-size, longer axis
17174
0
    float hs_h; // Half-size, smaller axis
17175
0
    ImVec2 off; // Distance from edge or center
17176
0
    if (outer_docking)
17177
0
    {
17178
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17179
        //hs_h = ImTrunc(hs_w * 0.15f);
17180
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17181
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17182
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17183
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17184
0
    }
17185
0
    else
17186
0
    {
17187
0
        hs_w = ImTrunc(hs_for_central_nodes);
17188
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17189
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17190
0
    }
17191
17192
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17193
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17194
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17195
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17196
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17197
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17198
17199
0
    if (test_mouse_pos == NULL)
17200
0
        return false;
17201
17202
0
    ImRect hit_r = out_r;
17203
0
    if (!outer_docking)
17204
0
    {
17205
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17206
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17207
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17208
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17209
0
        float r_threshold_center = hs_w * 1.4f;
17210
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17211
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17212
0
            return (dir == ImGuiDir_None);
17213
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17214
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17215
0
    }
17216
0
    return hit_r.Contains(*test_mouse_pos);
17217
0
}
17218
17219
// host_node may be NULL if the window doesn't have a DockNode already.
17220
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17221
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17222
0
{
17223
0
    ImGuiContext& g = *GImGui;
17224
17225
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17226
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17227
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17228
0
    if (payload_node == NULL)
17229
0
        payload_node = payload_window->DockNodeAsHost;
17230
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17231
0
    if (ref_node_for_rect)
17232
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17233
17234
    // Filter, figure out where we are allowed to dock
17235
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17236
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17237
0
    data->IsCenterAvailable = true;
17238
0
    if (is_outer_docking)
17239
0
        data->IsCenterAvailable = false;
17240
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17241
0
        data->IsCenterAvailable = false;
17242
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17243
0
        data->IsCenterAvailable = false;
17244
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17245
0
        data->IsCenterAvailable = false;
17246
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17247
0
        data->IsCenterAvailable = false;
17248
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17249
0
        data->IsCenterAvailable = false;
17250
17251
0
    data->IsSidesAvailable = true;
17252
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17253
0
        data->IsSidesAvailable = false;
17254
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17255
0
        data->IsSidesAvailable = false;
17256
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17257
0
        data->IsSidesAvailable = false;
17258
17259
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17260
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17261
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17262
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17263
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17264
17265
    // Calculate drop shapes geometry for allowed splitting directions
17266
0
    IM_ASSERT(ImGuiDir_None == -1);
17267
0
    data->SplitNode = host_node;
17268
0
    data->SplitDir = ImGuiDir_None;
17269
0
    data->IsSplitDirExplicit = false;
17270
0
    if (!host_window->Collapsed)
17271
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17272
0
        {
17273
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17274
0
                continue;
17275
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17276
0
                continue;
17277
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17278
0
            {
17279
0
                data->SplitDir = (ImGuiDir)dir;
17280
0
                data->IsSplitDirExplicit = true;
17281
0
            }
17282
0
        }
17283
17284
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17285
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17286
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17287
0
        data->IsDropAllowed = false;
17288
17289
    // Calculate split area
17290
0
    data->SplitRatio = 0.0f;
17291
0
    if (data->SplitDir != ImGuiDir_None)
17292
0
    {
17293
0
        ImGuiDir split_dir = data->SplitDir;
17294
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17295
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17296
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17297
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17298
17299
        // Calculate split ratio so we can pass it down the docking request
17300
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17301
0
        data->FutureNode.Pos = pos_new;
17302
0
        data->FutureNode.Size = size_new;
17303
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17304
0
    }
17305
0
}
17306
17307
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17308
0
{
17309
0
    ImGuiContext& g = *GImGui;
17310
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17311
17312
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17313
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17314
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17315
17316
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17317
0
    int overlay_draw_lists_count = 0;
17318
0
    ImDrawList* overlay_draw_lists[2];
17319
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17320
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17321
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17322
17323
    // Draw main preview rectangle
17324
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17325
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17326
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17327
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17328
17329
    // Display area preview
17330
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17331
0
    if (data->IsDropAllowed)
17332
0
    {
17333
0
        ImRect overlay_rect = data->FutureNode.Rect();
17334
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17335
0
            overlay_rect.Min.y += GetFrameHeight();
17336
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17337
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17338
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17339
0
    }
17340
17341
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17342
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17343
0
    {
17344
        // Compute target tab bar geometry so we can locate our preview tabs
17345
0
        ImRect tab_bar_rect;
17346
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17347
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17348
0
        if (host_node && host_node->TabBar)
17349
0
        {
17350
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17351
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17352
0
            else
17353
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17354
0
        }
17355
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17356
0
        {
17357
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17358
0
        }
17359
17360
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17361
0
        if (root_payload->DockNodeAsHost)
17362
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17363
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17364
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17365
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17366
0
        {
17367
            // DockNode's TabBar may have non-window Tabs manually appended by user
17368
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17369
0
            if (tab_bar_with_payload && payload_window == NULL)
17370
0
                continue;
17371
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17372
0
                continue;
17373
17374
            // Calculate the tab bounding box for each payload window
17375
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17376
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17377
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17378
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17379
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17380
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17381
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17382
0
            {
17383
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17384
0
                if (!tab_bar_rect.Contains(tab_bb))
17385
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17386
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17387
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17388
0
                if (!tab_bar_rect.Contains(tab_bb))
17389
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17390
0
            }
17391
0
            PopStyleColor();
17392
0
        }
17393
0
    }
17394
17395
    // Display drop boxes
17396
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17397
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17398
0
    {
17399
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17400
0
        {
17401
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17402
0
            ImRect draw_r_in = draw_r;
17403
0
            draw_r_in.Expand(-2.0f);
17404
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17405
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17406
0
            {
17407
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17408
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17409
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17410
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17411
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17412
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17413
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17414
0
            }
17415
0
        }
17416
17417
        // Stop after ImGuiDir_None
17418
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17419
0
            return;
17420
0
    }
17421
0
}
17422
17423
//-----------------------------------------------------------------------------
17424
// Docking: ImGuiDockNode Tree manipulation functions
17425
//-----------------------------------------------------------------------------
17426
// - DockNodeTreeSplit()
17427
// - DockNodeTreeMerge()
17428
// - DockNodeTreeUpdatePosSize()
17429
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17430
// - DockNodeTreeUpdateSplitter()
17431
// - DockNodeTreeFindFallbackLeafNode()
17432
// - DockNodeTreeFindNodeByPos()
17433
//-----------------------------------------------------------------------------
17434
17435
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17436
0
{
17437
0
    ImGuiContext& g = *GImGui;
17438
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17439
17440
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17441
0
    child_0->ParentNode = parent_node;
17442
17443
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17444
0
    child_1->ParentNode = parent_node;
17445
17446
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17447
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17448
0
    parent_node->ChildNodes[0] = child_0;
17449
0
    parent_node->ChildNodes[1] = child_1;
17450
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17451
0
    parent_node->SplitAxis = split_axis;
17452
0
    parent_node->VisibleWindow = NULL;
17453
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17454
17455
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17456
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17457
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17458
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17459
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17460
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17461
17462
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17463
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17464
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17465
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17466
17467
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17468
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17469
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17470
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17471
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17472
0
    child_0->UpdateMergedFlags();
17473
0
    child_1->UpdateMergedFlags();
17474
0
    parent_node->UpdateMergedFlags();
17475
0
    if (child_inheritor->IsCentralNode())
17476
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17477
0
}
17478
17479
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17480
0
{
17481
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17482
0
    ImGuiContext& g = *GImGui;
17483
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17484
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17485
0
    IM_ASSERT(child_0 || child_1);
17486
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17487
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17488
0
    {
17489
0
        IM_ASSERT(parent_node->TabBar == NULL);
17490
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17491
0
    }
17492
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17493
17494
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17495
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17496
0
    if (child_0)
17497
0
    {
17498
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17499
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17500
0
    }
17501
0
    if (child_1)
17502
0
    {
17503
0
        DockNodeMoveWindows(parent_node, child_1);
17504
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17505
0
    }
17506
0
    DockNodeApplyPosSizeToWindows(parent_node);
17507
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17508
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17509
0
    parent_node->SizeRef = backup_last_explicit_size;
17510
17511
    // Flags transfer
17512
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17513
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17514
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17515
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17516
0
    parent_node->UpdateMergedFlags();
17517
17518
0
    if (child_0)
17519
0
    {
17520
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17521
0
        IM_DELETE(child_0);
17522
0
    }
17523
0
    if (child_1)
17524
0
    {
17525
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17526
0
        IM_DELETE(child_1);
17527
0
    }
17528
0
}
17529
17530
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17531
// (Depth-first, Pre-Order)
17532
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17533
0
{
17534
    // During the regular dock node update we write to all nodes.
17535
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17536
0
    ImGuiContext& g = *GImGui;
17537
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17538
0
    if (write_to_node)
17539
0
    {
17540
0
        node->Pos = pos;
17541
0
        node->Size = size;
17542
0
    }
17543
17544
0
    if (node->IsLeafNode())
17545
0
        return;
17546
17547
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17548
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17549
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17550
0
    ImVec2 child_0_size = size, child_1_size = size;
17551
17552
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17553
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17554
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17555
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17556
17557
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17558
0
    {
17559
0
        const float spacing = g.Style.DockingSeparatorSize;
17560
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17561
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17562
17563
        // Size allocation policy
17564
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17565
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17566
17567
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17568
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
17569
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17570
17571
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17572
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17573
0
        {
17574
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17575
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17576
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17577
0
        }
17578
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17579
0
        {
17580
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17581
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17582
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17583
0
        }
17584
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17585
0
        {
17586
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17587
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17588
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17589
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
17590
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17591
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17592
0
        }
17593
17594
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17595
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17596
0
        {
17597
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17598
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17599
0
        }
17600
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17601
0
        {
17602
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17603
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17604
0
        }
17605
0
        else
17606
0
        {
17607
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17608
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17609
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
17610
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17611
0
        }
17612
17613
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17614
0
    }
17615
17616
0
    if (only_write_to_single_node == NULL)
17617
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17618
17619
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17620
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17621
0
    if (child_0_recurse)
17622
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17623
0
    if (child_1_recurse)
17624
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17625
0
}
17626
17627
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17628
0
{
17629
0
    if (node->IsLeafNode())
17630
0
    {
17631
0
        touching_nodes->push_back(node);
17632
0
        return;
17633
0
    }
17634
0
    if (node->ChildNodes[0]->IsVisible)
17635
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17636
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17637
0
    if (node->ChildNodes[1]->IsVisible)
17638
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17639
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17640
0
}
17641
17642
// (Depth-First, Pre-Order)
17643
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17644
0
{
17645
0
    if (node->IsLeafNode())
17646
0
        return;
17647
17648
0
    ImGuiContext& g = *GImGui;
17649
17650
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17651
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17652
0
    if (child_0->IsVisible && child_1->IsVisible)
17653
0
    {
17654
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17655
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17656
0
        IM_ASSERT(axis != ImGuiAxis_None);
17657
0
        ImRect bb;
17658
0
        bb.Min = child_0->Pos;
17659
0
        bb.Max = child_1->Pos;
17660
0
        bb.Min[axis] += child_0->Size[axis];
17661
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17662
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17663
17664
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17665
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17666
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17667
0
        {
17668
0
            ImGuiWindow* window = g.CurrentWindow;
17669
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17670
0
        }
17671
0
        else
17672
0
        {
17673
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17674
            //bb.Max[axis] -= 1;
17675
0
            PushID(node->ID);
17676
17677
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17678
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17679
0
            float min_size = g.Style.WindowMinSize[axis];
17680
0
            float resize_limits[2];
17681
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17682
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17683
17684
0
            ImGuiID splitter_id = GetID("##Splitter");
17685
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17686
0
            {
17687
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17688
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17689
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17690
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17691
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17692
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17693
17694
                // [DEBUG] Render touching nodes & limits
17695
                /*
17696
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17697
                for (int n = 0; n < 2; n++)
17698
                {
17699
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17700
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17701
                    if (axis == ImGuiAxis_X)
17702
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17703
                    else
17704
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17705
                }
17706
                */
17707
0
            }
17708
17709
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17710
0
            float cur_size_0 = child_0->Size[axis];
17711
0
            float cur_size_1 = child_1->Size[axis];
17712
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17713
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17714
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17715
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17716
0
            {
17717
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17718
0
                {
17719
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17720
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17721
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17722
17723
                    // Lock the size of every node that is a sibling of the node we are touching
17724
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17725
0
                    for (int side_n = 0; side_n < 2; side_n++)
17726
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17727
0
                        {
17728
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17729
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17730
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17731
0
                            while (touching_node->ParentNode != node)
17732
0
                            {
17733
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17734
0
                                {
17735
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17736
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17737
0
                                    node_to_preserve->WantLockSizeOnce = true;
17738
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17739
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17740
0
                                }
17741
0
                                touching_node = touching_node->ParentNode;
17742
0
                            }
17743
0
                        }
17744
17745
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17746
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17747
0
                    MarkIniSettingsDirty();
17748
0
                }
17749
0
            }
17750
0
            PopID();
17751
0
        }
17752
0
    }
17753
17754
0
    if (child_0->IsVisible)
17755
0
        DockNodeTreeUpdateSplitter(child_0);
17756
0
    if (child_1->IsVisible)
17757
0
        DockNodeTreeUpdateSplitter(child_1);
17758
0
}
17759
17760
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17761
0
{
17762
0
    if (node->IsLeafNode())
17763
0
        return node;
17764
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17765
0
        return leaf_node;
17766
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17767
0
        return leaf_node;
17768
0
    return NULL;
17769
0
}
17770
17771
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17772
0
{
17773
0
    if (!node->IsVisible)
17774
0
        return NULL;
17775
17776
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17777
0
    ImRect r(node->Pos, node->Pos + node->Size);
17778
0
    r.Expand(dock_spacing * 0.5f);
17779
0
    bool inside = r.Contains(pos);
17780
0
    if (!inside)
17781
0
        return NULL;
17782
17783
0
    if (node->IsLeafNode())
17784
0
        return node;
17785
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17786
0
        return hovered_node;
17787
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17788
0
        return hovered_node;
17789
17790
    // This means we are hovering over the splitter/spacing of a parent node
17791
0
    return node;
17792
0
}
17793
17794
//-----------------------------------------------------------------------------
17795
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17796
//-----------------------------------------------------------------------------
17797
// - SetWindowDock() [Internal]
17798
// - DockSpace()
17799
// - DockSpaceOverViewport()
17800
//-----------------------------------------------------------------------------
17801
17802
// [Internal] Called via SetNextWindowDockID()
17803
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17804
0
{
17805
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17806
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17807
0
        return;
17808
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17809
17810
0
    if (window->DockId == dock_id)
17811
0
        return;
17812
17813
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17814
0
    ImGuiContext* ctx = GImGui;
17815
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17816
0
        if (new_node->IsSplitNode())
17817
0
        {
17818
            // Policy: Find central node or latest focused node. We first move back to our root node.
17819
0
            new_node = DockNodeGetRootNode(new_node);
17820
0
            if (new_node->CentralNode)
17821
0
            {
17822
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17823
0
                dock_id = new_node->CentralNode->ID;
17824
0
            }
17825
0
            else
17826
0
            {
17827
0
                dock_id = new_node->LastFocusedNodeId;
17828
0
            }
17829
0
        }
17830
17831
0
    if (window->DockId == dock_id)
17832
0
        return;
17833
17834
0
    if (window->DockNode)
17835
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17836
0
    window->DockId = dock_id;
17837
0
}
17838
17839
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17840
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17841
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17842
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17843
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17844
0
{
17845
0
    ImGuiContext* ctx = GImGui;
17846
0
    ImGuiContext& g = *ctx;
17847
0
    ImGuiWindow* window = GetCurrentWindowRead();
17848
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17849
0
        return 0;
17850
17851
    // Early out if parent window is hidden/collapsed
17852
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17853
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17854
0
    if (window->SkipItems)
17855
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17856
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17857
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17858
17859
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17860
0
    IM_ASSERT(id != 0);
17861
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17862
0
    if (!node)
17863
0
    {
17864
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17865
0
        node = DockContextAddNode(ctx, id);
17866
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17867
0
    }
17868
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17869
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17870
0
    node->SharedFlags = flags;
17871
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17872
17873
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17874
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17875
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17876
0
    {
17877
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17878
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17879
0
        return id;
17880
0
    }
17881
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17882
17883
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17884
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17885
0
    {
17886
0
        node->LastFrameAlive = g.FrameCount;
17887
0
        return id;
17888
0
    }
17889
17890
0
    const ImVec2 content_avail = GetContentRegionAvail();
17891
0
    ImVec2 size = ImTrunc(size_arg);
17892
0
    if (size.x <= 0.0f)
17893
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17894
0
    if (size.y <= 0.0f)
17895
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17896
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17897
17898
0
    node->Pos = window->DC.CursorPos;
17899
0
    node->Size = node->SizeRef = size;
17900
0
    SetNextWindowPos(node->Pos);
17901
0
    SetNextWindowSize(node->Size);
17902
0
    g.NextWindowData.PosUndock = false;
17903
17904
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17905
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17906
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17907
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17908
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17909
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17910
17911
0
    char title[256];
17912
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17913
17914
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17915
0
    Begin(title, NULL, window_flags);
17916
0
    PopStyleVar();
17917
17918
0
    ImGuiWindow* host_window = g.CurrentWindow;
17919
0
    DockNodeSetupHostWindow(node, host_window);
17920
0
    host_window->ChildId = window->GetID(title);
17921
0
    node->OnlyNodeWithWindows = NULL;
17922
17923
0
    IM_ASSERT(node->IsRootNode());
17924
17925
    // We need to handle the rare case were a central node is missing.
17926
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17927
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17928
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17929
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17930
    // as it doesn't make sense for an empty dockspace to not have this property.
17931
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17932
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17933
17934
    // Update the node
17935
0
    DockNodeUpdate(node);
17936
17937
0
    End();
17938
17939
0
    ImRect bb(node->Pos, node->Pos + size);
17940
0
    ItemSize(size);
17941
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
17942
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
17943
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
17944
17945
0
    return id;
17946
0
}
17947
17948
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17949
// The limitation with this call is that your window won't have a menu bar.
17950
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17951
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17952
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17953
0
{
17954
0
    if (viewport == NULL)
17955
0
        viewport = GetMainViewport();
17956
17957
0
    SetNextWindowPos(viewport->WorkPos);
17958
0
    SetNextWindowSize(viewport->WorkSize);
17959
0
    SetNextWindowViewport(viewport->ID);
17960
17961
0
    ImGuiWindowFlags host_window_flags = 0;
17962
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17963
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17964
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17965
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17966
17967
0
    char label[32];
17968
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17969
17970
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17971
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17972
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17973
0
    Begin(label, NULL, host_window_flags);
17974
0
    PopStyleVar(3);
17975
17976
0
    ImGuiID dockspace_id = GetID("DockSpace");
17977
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17978
0
    End();
17979
17980
0
    return dockspace_id;
17981
0
}
17982
17983
//-----------------------------------------------------------------------------
17984
// Docking: Builder Functions
17985
//-----------------------------------------------------------------------------
17986
// Very early end-user API to manipulate dock nodes.
17987
// Only available in imgui_internal.h. Expect this API to change/break!
17988
// It is expected that those functions are all called _before_ the dockspace node submission.
17989
//-----------------------------------------------------------------------------
17990
// - DockBuilderDockWindow()
17991
// - DockBuilderGetNode()
17992
// - DockBuilderSetNodePos()
17993
// - DockBuilderSetNodeSize()
17994
// - DockBuilderAddNode()
17995
// - DockBuilderRemoveNode()
17996
// - DockBuilderRemoveNodeChildNodes()
17997
// - DockBuilderRemoveNodeDockedWindows()
17998
// - DockBuilderSplitNode()
17999
// - DockBuilderCopyNodeRec()
18000
// - DockBuilderCopyNode()
18001
// - DockBuilderCopyWindowSettings()
18002
// - DockBuilderCopyDockSpace()
18003
// - DockBuilderFinish()
18004
//-----------------------------------------------------------------------------
18005
18006
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18007
0
{
18008
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18009
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18010
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18011
0
    ImGuiID window_id = ImHashStr(window_name);
18012
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18013
0
    {
18014
        // Apply to created window
18015
0
        ImGuiID prev_node_id = window->DockId;
18016
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18017
0
        if (window->DockId != prev_node_id)
18018
0
            window->DockOrder = -1;
18019
0
    }
18020
0
    else
18021
0
    {
18022
        // Apply to settings
18023
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18024
0
        if (settings == NULL)
18025
0
            settings = CreateNewWindowSettings(window_name);
18026
0
        if (settings->DockId != node_id)
18027
0
            settings->DockOrder = -1;
18028
0
        settings->DockId = node_id;
18029
0
    }
18030
0
}
18031
18032
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18033
0
{
18034
0
    ImGuiContext* ctx = GImGui;
18035
0
    return DockContextFindNodeByID(ctx, node_id);
18036
0
}
18037
18038
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18039
0
{
18040
0
    ImGuiContext* ctx = GImGui;
18041
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18042
0
    if (node == NULL)
18043
0
        return;
18044
0
    node->Pos = pos;
18045
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18046
0
}
18047
18048
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18049
0
{
18050
0
    ImGuiContext* ctx = GImGui;
18051
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18052
0
    if (node == NULL)
18053
0
        return;
18054
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18055
0
    node->Size = node->SizeRef = size;
18056
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18057
0
}
18058
18059
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18060
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18061
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18062
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18063
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18064
// - Use (id == 0) to let the system allocate a node identifier.
18065
// - Existing node with a same id will be removed.
18066
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18067
0
{
18068
0
    ImGuiContext* ctx = GImGui;
18069
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18070
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18071
18072
0
    if (node_id != 0)
18073
0
        DockBuilderRemoveNode(node_id);
18074
18075
0
    ImGuiDockNode* node = NULL;
18076
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18077
0
    {
18078
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18079
0
        node = DockContextFindNodeByID(ctx, node_id);
18080
0
    }
18081
0
    else
18082
0
    {
18083
0
        node = DockContextAddNode(ctx, node_id);
18084
0
        node->SetLocalFlags(flags);
18085
0
    }
18086
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18087
0
    return node->ID;
18088
0
}
18089
18090
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18091
0
{
18092
0
    ImGuiContext* ctx = GImGui;
18093
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18094
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18095
18096
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18097
0
    if (node == NULL)
18098
0
        return;
18099
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18100
0
    DockBuilderRemoveNodeChildNodes(node_id);
18101
    // Node may have moved or deleted if e.g. any merge happened
18102
0
    node = DockContextFindNodeByID(ctx, node_id);
18103
0
    if (node == NULL)
18104
0
        return;
18105
0
    if (node->IsCentralNode() && node->ParentNode)
18106
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18107
0
    DockContextRemoveNode(ctx, node, true);
18108
0
}
18109
18110
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18111
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18112
0
{
18113
0
    ImGuiContext* ctx = GImGui;
18114
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18115
18116
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
18117
0
    if (root_id && root_node == NULL)
18118
0
        return;
18119
0
    bool has_central_node = false;
18120
18121
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18122
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18123
18124
    // Process active windows
18125
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18126
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18127
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18128
0
        {
18129
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18130
0
            if (want_removal)
18131
0
            {
18132
0
                if (node->IsCentralNode())
18133
0
                    has_central_node = true;
18134
0
                if (root_id != 0)
18135
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
18136
0
                if (root_node)
18137
0
                {
18138
0
                    DockNodeMoveWindows(root_node, node);
18139
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18140
0
                }
18141
0
                nodes_to_remove.push_back(node);
18142
0
            }
18143
0
        }
18144
18145
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18146
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18147
0
    if (root_node)
18148
0
    {
18149
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18150
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18151
0
    }
18152
18153
    // Apply to settings
18154
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
18155
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18156
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18157
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18158
0
                {
18159
0
                    settings->DockId = root_id;
18160
0
                    break;
18161
0
                }
18162
18163
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18164
0
    if (nodes_to_remove.Size > 1)
18165
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18166
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18167
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
18168
18169
0
    if (root_id == 0)
18170
0
    {
18171
0
        dc->Nodes.Clear();
18172
0
        dc->Requests.clear();
18173
0
    }
18174
0
    else if (has_central_node)
18175
0
    {
18176
0
        root_node->CentralNode = root_node;
18177
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18178
0
    }
18179
0
}
18180
18181
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18182
0
{
18183
    // Clear references in settings
18184
0
    ImGuiContext* ctx = GImGui;
18185
0
    ImGuiContext& g = *ctx;
18186
0
    if (clear_settings_refs)
18187
0
    {
18188
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18189
0
        {
18190
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18191
0
            if (!want_removal && settings->DockId != 0)
18192
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
18193
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18194
0
                        want_removal = true;
18195
0
            if (want_removal)
18196
0
                settings->DockId = 0;
18197
0
        }
18198
0
    }
18199
18200
    // Clear references in windows
18201
0
    for (int n = 0; n < g.Windows.Size; n++)
18202
0
    {
18203
0
        ImGuiWindow* window = g.Windows[n];
18204
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18205
0
        if (want_removal)
18206
0
        {
18207
0
            const ImGuiID backup_dock_id = window->DockId;
18208
0
            IM_UNUSED(backup_dock_id);
18209
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
18210
0
            if (!clear_settings_refs)
18211
0
                IM_ASSERT(window->DockId == backup_dock_id);
18212
0
        }
18213
0
    }
18214
0
}
18215
18216
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18217
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18218
// FIXME-DOCK: We are not exposing nor using split_outer.
18219
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18220
0
{
18221
0
    ImGuiContext& g = *GImGui;
18222
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18223
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18224
18225
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18226
0
    if (node == NULL)
18227
0
    {
18228
0
        IM_ASSERT(node != NULL);
18229
0
        return 0;
18230
0
    }
18231
18232
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18233
18234
0
    ImGuiDockRequest req;
18235
0
    req.Type = ImGuiDockRequestType_Split;
18236
0
    req.DockTargetWindow = NULL;
18237
0
    req.DockTargetNode = node;
18238
0
    req.DockPayload = NULL;
18239
0
    req.DockSplitDir = split_dir;
18240
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18241
0
    req.DockSplitOuter = false;
18242
0
    DockContextProcessDock(&g, &req);
18243
18244
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18245
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18246
0
    if (out_id_at_dir)
18247
0
        *out_id_at_dir = id_at_dir;
18248
0
    if (out_id_at_opposite_dir)
18249
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18250
0
    return id_at_dir;
18251
0
}
18252
18253
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18254
0
{
18255
0
    ImGuiContext& g = *GImGui;
18256
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18257
0
    dst_node->SharedFlags = src_node->SharedFlags;
18258
0
    dst_node->LocalFlags = src_node->LocalFlags;
18259
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18260
0
    dst_node->Pos = src_node->Pos;
18261
0
    dst_node->Size = src_node->Size;
18262
0
    dst_node->SizeRef = src_node->SizeRef;
18263
0
    dst_node->SplitAxis = src_node->SplitAxis;
18264
0
    dst_node->UpdateMergedFlags();
18265
18266
0
    out_node_remap_pairs->push_back(src_node->ID);
18267
0
    out_node_remap_pairs->push_back(dst_node->ID);
18268
18269
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18270
0
        if (src_node->ChildNodes[child_n])
18271
0
        {
18272
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18273
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18274
0
        }
18275
18276
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18277
0
    return dst_node;
18278
0
}
18279
18280
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18281
0
{
18282
0
    ImGuiContext* ctx = GImGui;
18283
0
    IM_ASSERT(src_node_id != 0);
18284
0
    IM_ASSERT(dst_node_id != 0);
18285
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18286
18287
0
    DockBuilderRemoveNode(dst_node_id);
18288
18289
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
18290
0
    IM_ASSERT(src_node != NULL);
18291
18292
0
    out_node_remap_pairs->clear();
18293
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18294
18295
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18296
0
}
18297
18298
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18299
0
{
18300
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18301
0
    if (src_window == NULL)
18302
0
        return;
18303
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18304
0
    {
18305
0
        dst_window->Pos = src_window->Pos;
18306
0
        dst_window->Size = src_window->Size;
18307
0
        dst_window->SizeFull = src_window->SizeFull;
18308
0
        dst_window->Collapsed = src_window->Collapsed;
18309
0
    }
18310
0
    else
18311
0
    {
18312
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18313
0
        if (!dst_settings)
18314
0
            dst_settings = CreateNewWindowSettings(dst_name);
18315
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18316
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18317
0
        {
18318
0
            dst_settings->ViewportPos = window_pos_2ih;
18319
0
            dst_settings->ViewportId = src_window->ViewportId;
18320
0
            dst_settings->Pos = ImVec2ih(0, 0);
18321
0
        }
18322
0
        else
18323
0
        {
18324
0
            dst_settings->Pos = window_pos_2ih;
18325
0
        }
18326
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18327
0
        dst_settings->Collapsed = src_window->Collapsed;
18328
0
    }
18329
0
}
18330
18331
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18332
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18333
0
{
18334
0
    ImGuiContext& g = *GImGui;
18335
0
    IM_ASSERT(src_dockspace_id != 0);
18336
0
    IM_ASSERT(dst_dockspace_id != 0);
18337
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18338
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18339
18340
    // Duplicate entire dock
18341
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18342
    // whereas we could attempt to at least keep them together in a new, same floating node.
18343
0
    ImVector<ImGuiID> node_remap_pairs;
18344
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18345
18346
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18347
    // (The windows associated to src_dockspace_id are staying in place)
18348
0
    ImVector<ImGuiID> src_windows;
18349
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18350
0
    {
18351
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18352
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18353
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18354
0
        src_windows.push_back(src_window_id);
18355
18356
        // Search in the remapping tables
18357
0
        ImGuiID src_dock_id = 0;
18358
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18359
0
            src_dock_id = src_window->DockId;
18360
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18361
0
            src_dock_id = src_window_settings->DockId;
18362
0
        ImGuiID dst_dock_id = 0;
18363
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18364
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18365
0
            {
18366
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18367
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18368
0
                break;
18369
0
            }
18370
18371
0
        if (dst_dock_id != 0)
18372
0
        {
18373
            // Docked windows gets redocked into the new node hierarchy.
18374
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18375
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18376
0
        }
18377
0
        else
18378
0
        {
18379
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18380
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18381
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18382
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18383
0
        }
18384
0
    }
18385
18386
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18387
    // Find those windows and move to them to the cloned dock node. This may be optional?
18388
    // Dock those are a second step as undocking would invalidate source dock nodes.
18389
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18390
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18391
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18392
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18393
0
        {
18394
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18395
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18396
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18397
0
            {
18398
0
                ImGuiWindow* window = node->Windows[window_n];
18399
0
                if (src_windows.contains(window->ID))
18400
0
                    continue;
18401
18402
                // Docked windows gets redocked into the new node hierarchy.
18403
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18404
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18405
0
            }
18406
0
        }
18407
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18408
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18409
0
}
18410
18411
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18412
void ImGui::DockBuilderFinish(ImGuiID root_id)
18413
0
{
18414
0
    ImGuiContext* ctx = GImGui;
18415
    //DockContextRebuild(ctx);
18416
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18417
0
}
18418
18419
//-----------------------------------------------------------------------------
18420
// Docking: Begin/End Support Functions (called from Begin/End)
18421
//-----------------------------------------------------------------------------
18422
// - GetWindowAlwaysWantOwnTabBar()
18423
// - DockContextBindNodeToWindow()
18424
// - BeginDocked()
18425
// - BeginDockableDragDropSource()
18426
// - BeginDockableDragDropTarget()
18427
//-----------------------------------------------------------------------------
18428
18429
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18430
159k
{
18431
159k
    ImGuiContext& g = *GImGui;
18432
159k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18433
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18434
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18435
0
                return true;
18436
159k
    return false;
18437
159k
}
18438
18439
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18440
0
{
18441
0
    ImGuiContext& g = *ctx;
18442
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18443
0
    IM_ASSERT(window->DockNode == NULL);
18444
18445
    // We should not be docking into a split node (SetWindowDock should avoid this)
18446
0
    if (node && node->IsSplitNode())
18447
0
    {
18448
0
        DockContextProcessUndockWindow(ctx, window);
18449
0
        return NULL;
18450
0
    }
18451
18452
    // Create node
18453
0
    if (node == NULL)
18454
0
    {
18455
0
        node = DockContextAddNode(ctx, window->DockId);
18456
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18457
0
        node->LastFrameAlive = g.FrameCount;
18458
0
    }
18459
18460
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18461
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18462
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18463
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18464
0
    if (!node->IsVisible)
18465
0
    {
18466
0
        ImGuiDockNode* ancestor_node = node;
18467
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18468
0
            ancestor_node = ancestor_node->ParentNode;
18469
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18470
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18471
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18472
0
    }
18473
18474
    // Add window to node
18475
0
    bool node_was_visible = node->IsVisible;
18476
0
    DockNodeAddWindow(node, window, true);
18477
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18478
0
    IM_ASSERT(node == window->DockNode);
18479
0
    return node;
18480
0
}
18481
18482
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18483
0
{
18484
0
    ImGuiContext* ctx = GImGui;
18485
0
    ImGuiContext& g = *ctx;
18486
18487
    // Clear fields ahead so most early-out paths don't have to do it
18488
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18489
18490
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18491
0
    if (auto_dock_node)
18492
0
    {
18493
0
        if (window->DockId == 0)
18494
0
        {
18495
0
            IM_ASSERT(window->DockNode == NULL);
18496
0
            window->DockId = DockContextGenNodeID(ctx);
18497
0
        }
18498
0
    }
18499
0
    else
18500
0
    {
18501
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18502
0
        bool want_undock = false;
18503
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18504
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18505
0
        if (want_undock)
18506
0
        {
18507
0
            DockContextProcessUndockWindow(ctx, window);
18508
0
            return;
18509
0
        }
18510
0
    }
18511
18512
    // Bind to our dock node
18513
0
    ImGuiDockNode* node = window->DockNode;
18514
0
    if (node != NULL)
18515
0
        IM_ASSERT(window->DockId == node->ID);
18516
0
    if (window->DockId != 0 && node == NULL)
18517
0
    {
18518
0
        node = DockContextBindNodeToWindow(ctx, window);
18519
0
        if (node == NULL)
18520
0
            return;
18521
0
    }
18522
18523
#if 0
18524
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18525
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18526
    {
18527
        DockContextProcessUndockWindow(ctx, window);
18528
        return;
18529
    }
18530
#endif
18531
18532
    // Undock if our dockspace node disappeared
18533
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18534
0
    if (node->LastFrameAlive < g.FrameCount)
18535
0
    {
18536
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18537
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18538
0
        if (root_node->LastFrameAlive < g.FrameCount)
18539
0
            DockContextProcessUndockWindow(ctx, window);
18540
0
        else
18541
0
            window->DockIsActive = true;
18542
0
        return;
18543
0
    }
18544
18545
    // Store style overrides
18546
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18547
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18548
18549
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18550
    // and never create neither a host window neither a tab bar.
18551
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18552
0
    if (node->HostWindow == NULL)
18553
0
    {
18554
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18555
0
            window->DockIsActive = true;
18556
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
18557
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18558
0
        return;
18559
0
    }
18560
18561
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18562
0
    IM_ASSERT(node->HostWindow);
18563
0
    IM_ASSERT(node->IsLeafNode());
18564
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18565
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18566
18567
    // Undock if we are submitted earlier than the host window
18568
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18569
0
    {
18570
0
        DockContextProcessUndockWindow(ctx, window);
18571
0
        return;
18572
0
    }
18573
18574
    // Position/Size window
18575
0
    SetNextWindowPos(node->Pos);
18576
0
    SetNextWindowSize(node->Size);
18577
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18578
0
    window->DockIsActive = true;
18579
0
    window->DockNodeIsVisible = true;
18580
0
    window->DockTabIsVisible = false;
18581
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18582
0
        return;
18583
18584
    // When the window is selected we mark it as visible.
18585
0
    if (node->VisibleWindow == window)
18586
0
        window->DockTabIsVisible = true;
18587
18588
    // Update window flag
18589
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18590
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18591
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18592
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18593
0
    else
18594
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18595
18596
    // Save new dock order only if the window has been visible once already
18597
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18598
0
    if (node->TabBar && window->WasActive)
18599
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18600
18601
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18602
0
        *p_open = false;
18603
18604
    // Update ChildId to allow returning from Child to Parent with Escape
18605
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18606
0
    window->ChildId = parent_window->GetID(window->Name);
18607
0
}
18608
18609
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18610
30
{
18611
30
    ImGuiContext& g = *GImGui;
18612
30
    IM_ASSERT(g.ActiveId == window->MoveId);
18613
30
    IM_ASSERT(g.MovingWindow == window);
18614
30
    IM_ASSERT(g.CurrentWindow == window);
18615
18616
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
18617
30
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
18618
0
    {
18619
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
18620
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
18621
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
18622
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
18623
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
18624
0
        return;
18625
0
    }
18626
18627
30
    g.LastItemData.ID = window->MoveId;
18628
30
    window = window->RootWindowDockTree;
18629
30
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18630
30
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18631
30
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18632
3
    {
18633
3
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18634
3
        EndDragDropSource();
18635
18636
        // Store style overrides
18637
21
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18638
18
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18639
3
    }
18640
30
}
18641
18642
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18643
9
{
18644
9
    ImGuiContext* ctx = GImGui;
18645
9
    ImGuiContext& g = *ctx;
18646
18647
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18648
9
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18649
9
    if (!g.DragDropActive)
18650
0
        return;
18651
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18652
9
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18653
9
        return;
18654
18655
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18656
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18657
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18658
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18659
0
    {
18660
0
        EndDragDropTarget();
18661
0
        return;
18662
0
    }
18663
18664
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18665
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18666
0
    {
18667
        // Select target node
18668
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18669
0
        bool dock_into_floating_window = false;
18670
0
        ImGuiDockNode* node = NULL;
18671
0
        if (window->DockNodeAsHost)
18672
0
        {
18673
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18674
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18675
18676
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18677
            // In this case we need to fallback into any leaf mode, possibly the central node.
18678
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18679
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18680
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18681
0
        }
18682
0
        else
18683
0
        {
18684
0
            if (window->DockNode)
18685
0
                node = window->DockNode;
18686
0
            else
18687
0
                dock_into_floating_window = true; // Dock into a regular window
18688
0
        }
18689
18690
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18691
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18692
18693
        // Preview docking request and find out split direction/ratio
18694
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18695
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18696
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18697
0
        {
18698
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18699
0
            ImGuiDockPreviewData split_inner;
18700
0
            ImGuiDockPreviewData split_outer;
18701
0
            ImGuiDockPreviewData* split_data = &split_inner;
18702
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18703
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18704
0
                {
18705
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18706
0
                    if (split_outer.IsSplitDirExplicit)
18707
0
                        split_data = &split_outer;
18708
0
                }
18709
0
            if (!node || node->IsLeafNode())
18710
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18711
0
            if (split_data == &split_outer)
18712
0
                split_inner.IsDropAllowed = false;
18713
18714
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18715
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18716
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18717
18718
            // Queue docking request
18719
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18720
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18721
0
        }
18722
0
    }
18723
0
    EndDragDropTarget();
18724
0
}
18725
18726
//-----------------------------------------------------------------------------
18727
// Docking: Settings
18728
//-----------------------------------------------------------------------------
18729
// - DockSettingsRenameNodeReferences()
18730
// - DockSettingsRemoveNodeReferences()
18731
// - DockSettingsFindNodeSettings()
18732
// - DockSettingsHandler_ApplyAll()
18733
// - DockSettingsHandler_ReadOpen()
18734
// - DockSettingsHandler_ReadLine()
18735
// - DockSettingsHandler_DockNodeToSettings()
18736
// - DockSettingsHandler_WriteAll()
18737
//-----------------------------------------------------------------------------
18738
18739
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18740
0
{
18741
0
    ImGuiContext& g = *GImGui;
18742
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18743
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18744
0
    {
18745
0
        ImGuiWindow* window = g.Windows[window_n];
18746
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18747
0
            window->DockId = new_node_id;
18748
0
    }
18749
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18750
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18751
0
        if (settings->DockId == old_node_id)
18752
0
            settings->DockId = new_node_id;
18753
0
}
18754
18755
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18756
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18757
0
{
18758
0
    ImGuiContext& g = *GImGui;
18759
0
    int found = 0;
18760
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18761
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18762
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18763
0
            if (settings->DockId == node_ids[node_n])
18764
0
            {
18765
0
                settings->DockId = 0;
18766
0
                settings->DockOrder = -1;
18767
0
                if (++found < node_ids_count)
18768
0
                    break;
18769
0
                return;
18770
0
            }
18771
0
}
18772
18773
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18774
0
{
18775
    // FIXME-OPT
18776
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18777
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18778
0
        if (dc->NodesSettings[n].ID == id)
18779
0
            return &dc->NodesSettings[n];
18780
0
    return NULL;
18781
0
}
18782
18783
// Clear settings data
18784
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18785
0
{
18786
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18787
0
    dc->NodesSettings.clear();
18788
0
    DockContextClearNodes(ctx, 0, true);
18789
0
}
18790
18791
// Recreate nodes based on settings data
18792
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18793
0
{
18794
    // Prune settings at boot time only
18795
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18796
0
    if (ctx->Windows.Size == 0)
18797
0
        DockContextPruneUnusedSettingsNodes(ctx);
18798
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18799
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18800
0
}
18801
18802
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18803
0
{
18804
0
    if (strcmp(name, "Data") != 0)
18805
0
        return NULL;
18806
0
    return (void*)1;
18807
0
}
18808
18809
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18810
0
{
18811
0
    char c = 0;
18812
0
    int x = 0, y = 0;
18813
0
    int r = 0;
18814
18815
    // Parsing, e.g.
18816
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18817
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18818
    // Important: this code expect currently fields in a fixed order.
18819
0
    ImGuiDockNodeSettings node;
18820
0
    line = ImStrSkipBlank(line);
18821
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18822
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18823
0
    else return;
18824
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18825
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18826
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18827
0
    if (node.ParentNodeId == 0)
18828
0
    {
18829
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18830
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18831
0
    }
18832
0
    else
18833
0
    {
18834
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18835
0
    }
18836
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18837
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18838
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18839
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18840
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18841
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18842
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18843
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18844
0
    if (node.ParentNodeId != 0)
18845
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18846
0
            node.Depth = parent_settings->Depth + 1;
18847
0
    ctx->DockContext.NodesSettings.push_back(node);
18848
0
}
18849
18850
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18851
0
{
18852
0
    ImGuiDockNodeSettings node_settings;
18853
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18854
0
    node_settings.ID = node->ID;
18855
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18856
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18857
0
    node_settings.SelectedTabId = node->SelectedTabId;
18858
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18859
0
    node_settings.Depth = (char)depth;
18860
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18861
0
    node_settings.Pos = ImVec2ih(node->Pos);
18862
0
    node_settings.Size = ImVec2ih(node->Size);
18863
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18864
0
    dc->NodesSettings.push_back(node_settings);
18865
0
    if (node->ChildNodes[0])
18866
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18867
0
    if (node->ChildNodes[1])
18868
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18869
0
}
18870
18871
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18872
0
{
18873
0
    ImGuiContext& g = *ctx;
18874
0
    ImGuiDockContext* dc = &ctx->DockContext;
18875
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18876
0
        return;
18877
18878
    // Gather settings data
18879
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18880
0
    dc->NodesSettings.resize(0);
18881
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18882
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18883
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18884
0
            if (node->IsRootNode())
18885
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18886
18887
0
    int max_depth = 0;
18888
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18889
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18890
18891
    // Write to text buffer
18892
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18893
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18894
0
    {
18895
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18896
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18897
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18898
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18899
0
        if (node_settings->ParentNodeId)
18900
0
        {
18901
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18902
0
        }
18903
0
        else
18904
0
        {
18905
0
            if (node_settings->ParentWindowId)
18906
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18907
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18908
0
        }
18909
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18910
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18911
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18912
0
            buf->appendf(" NoResize=1");
18913
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18914
0
            buf->appendf(" CentralNode=1");
18915
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18916
0
            buf->appendf(" NoTabBar=1");
18917
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18918
0
            buf->appendf(" HiddenTabBar=1");
18919
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18920
0
            buf->appendf(" NoWindowMenuButton=1");
18921
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18922
0
            buf->appendf(" NoCloseButton=1");
18923
0
        if (node_settings->SelectedTabId)
18924
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18925
18926
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
18927
0
        if (g.IO.ConfigDebugIniSettings)
18928
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18929
0
            {
18930
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18931
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18932
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18933
                // Iterate settings so we can give info about windows that didn't exist during the session.
18934
0
                int contains_window = 0;
18935
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18936
0
                    if (settings->DockId == node_settings->ID)
18937
0
                    {
18938
0
                        if (contains_window++ == 0)
18939
0
                            buf->appendf(" ; contains ");
18940
0
                        buf->appendf("'%s' ", settings->GetName());
18941
0
                    }
18942
0
            }
18943
18944
0
        buf->appendf("\n");
18945
0
    }
18946
0
    buf->appendf("\n");
18947
0
}
18948
18949
18950
//-----------------------------------------------------------------------------
18951
// [SECTION] PLATFORM DEPENDENT HELPERS
18952
//-----------------------------------------------------------------------------
18953
18954
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18955
18956
#ifdef _MSC_VER
18957
#pragma comment(lib, "user32")
18958
#pragma comment(lib, "kernel32")
18959
#endif
18960
18961
// Win32 clipboard implementation
18962
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18963
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18964
{
18965
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18966
    g.ClipboardHandlerData.clear();
18967
    if (!::OpenClipboard(NULL))
18968
        return NULL;
18969
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18970
    if (wbuf_handle == NULL)
18971
    {
18972
        ::CloseClipboard();
18973
        return NULL;
18974
    }
18975
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18976
    {
18977
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18978
        g.ClipboardHandlerData.resize(buf_len);
18979
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18980
    }
18981
    ::GlobalUnlock(wbuf_handle);
18982
    ::CloseClipboard();
18983
    return g.ClipboardHandlerData.Data;
18984
}
18985
18986
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18987
{
18988
    if (!::OpenClipboard(NULL))
18989
        return;
18990
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18991
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18992
    if (wbuf_handle == NULL)
18993
    {
18994
        ::CloseClipboard();
18995
        return;
18996
    }
18997
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18998
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18999
    ::GlobalUnlock(wbuf_handle);
19000
    ::EmptyClipboard();
19001
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19002
        ::GlobalFree(wbuf_handle);
19003
    ::CloseClipboard();
19004
}
19005
19006
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19007
19008
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19009
static PasteboardRef main_clipboard = 0;
19010
19011
// OSX clipboard implementation
19012
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19013
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19014
{
19015
    if (!main_clipboard)
19016
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19017
    PasteboardClear(main_clipboard);
19018
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19019
    if (cf_data)
19020
    {
19021
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19022
        CFRelease(cf_data);
19023
    }
19024
}
19025
19026
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19027
{
19028
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19029
    if (!main_clipboard)
19030
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19031
    PasteboardSynchronize(main_clipboard);
19032
19033
    ItemCount item_count = 0;
19034
    PasteboardGetItemCount(main_clipboard, &item_count);
19035
    for (ItemCount i = 0; i < item_count; i++)
19036
    {
19037
        PasteboardItemID item_id = 0;
19038
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19039
        CFArrayRef flavor_type_array = 0;
19040
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19041
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19042
        {
19043
            CFDataRef cf_data;
19044
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19045
            {
19046
                g.ClipboardHandlerData.clear();
19047
                int length = (int)CFDataGetLength(cf_data);
19048
                g.ClipboardHandlerData.resize(length + 1);
19049
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19050
                g.ClipboardHandlerData[length] = 0;
19051
                CFRelease(cf_data);
19052
                return g.ClipboardHandlerData.Data;
19053
            }
19054
        }
19055
    }
19056
    return NULL;
19057
}
19058
19059
#else
19060
19061
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19062
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19063
0
{
19064
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19065
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19066
0
}
19067
19068
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19069
0
{
19070
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19071
0
    g.ClipboardHandlerData.clear();
19072
0
    const char* text_end = text + strlen(text);
19073
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19074
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19075
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19076
0
}
19077
19078
#endif
19079
19080
// Win32 API IME support (for Asian languages, etc.)
19081
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19082
19083
#include <imm.h>
19084
#ifdef _MSC_VER
19085
#pragma comment(lib, "imm32")
19086
#endif
19087
19088
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19089
{
19090
    // Notify OS Input Method Editor of text input position
19091
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19092
    if (hwnd == 0)
19093
        return;
19094
19095
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19096
    if (HIMC himc = ::ImmGetContext(hwnd))
19097
    {
19098
        COMPOSITIONFORM composition_form = {};
19099
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19100
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19101
        composition_form.dwStyle = CFS_FORCE_POSITION;
19102
        ::ImmSetCompositionWindow(himc, &composition_form);
19103
        CANDIDATEFORM candidate_form = {};
19104
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19105
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19106
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19107
        ::ImmSetCandidateWindow(himc, &candidate_form);
19108
        ::ImmReleaseContext(hwnd, himc);
19109
    }
19110
}
19111
19112
#else
19113
19114
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19115
19116
#endif
19117
19118
//-----------------------------------------------------------------------------
19119
// [SECTION] METRICS/DEBUGGER WINDOW
19120
//-----------------------------------------------------------------------------
19121
// - RenderViewportThumbnail() [Internal]
19122
// - RenderViewportsThumbnails() [Internal]
19123
// - DebugTextEncoding()
19124
// - MetricsHelpMarker() [Internal]
19125
// - ShowFontAtlas() [Internal]
19126
// - ShowMetricsWindow()
19127
// - DebugNodeColumns() [Internal]
19128
// - DebugNodeDockNode() [Internal]
19129
// - DebugNodeDrawList() [Internal]
19130
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19131
// - DebugNodeFont() [Internal]
19132
// - DebugNodeFontGlyph() [Internal]
19133
// - DebugNodeStorage() [Internal]
19134
// - DebugNodeTabBar() [Internal]
19135
// - DebugNodeViewport() [Internal]
19136
// - DebugNodeWindow() [Internal]
19137
// - DebugNodeWindowSettings() [Internal]
19138
// - DebugNodeWindowsList() [Internal]
19139
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19140
//-----------------------------------------------------------------------------
19141
19142
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19143
19144
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19145
0
{
19146
0
    ImGuiContext& g = *GImGui;
19147
0
    ImGuiWindow* window = g.CurrentWindow;
19148
19149
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19150
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19151
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19152
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19153
0
    for (ImGuiWindow* thumb_window : g.Windows)
19154
0
    {
19155
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19156
0
            continue;
19157
0
        if (thumb_window->Viewport != viewport)
19158
0
            continue;
19159
19160
0
        ImRect thumb_r = thumb_window->Rect();
19161
0
        ImRect title_r = thumb_window->TitleBarRect();
19162
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19163
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
19164
0
        thumb_r.ClipWithFull(bb);
19165
0
        title_r.ClipWithFull(bb);
19166
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19167
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19168
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19169
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19170
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19171
0
    }
19172
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19173
0
}
19174
19175
static void RenderViewportsThumbnails()
19176
0
{
19177
0
    ImGuiContext& g = *GImGui;
19178
0
    ImGuiWindow* window = g.CurrentWindow;
19179
19180
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
19181
0
    float SCALE = 1.0f / 8.0f;
19182
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19183
0
    for (ImGuiViewportP* viewport : g.Viewports)
19184
0
        bb_full.Add(viewport->GetMainRect());
19185
0
    ImVec2 p = window->DC.CursorPos;
19186
0
    ImVec2 off = p - bb_full.Min * SCALE;
19187
0
    for (ImGuiViewportP* viewport : g.Viewports)
19188
0
    {
19189
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19190
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19191
0
    }
19192
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19193
0
}
19194
19195
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19196
0
{
19197
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19198
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19199
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19200
0
}
19201
19202
// Draw an arbitrary US keyboard layout to visualize translated keys
19203
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19204
0
{
19205
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
19206
0
    const float  key_rounding = 3.0f;
19207
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
19208
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
19209
0
    const float  key_face_rounding = 2.0f;
19210
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
19211
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19212
0
    const float  key_row_offset = 9.0f;
19213
19214
0
    ImVec2 board_min = GetCursorScreenPos();
19215
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19216
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19217
19218
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19219
0
    const KeyLayoutData keys_to_display[] =
19220
0
    {
19221
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19222
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19223
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19224
0
    };
19225
19226
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19227
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19228
0
    Dummy(board_max - board_min);
19229
0
    if (!IsItemVisible())
19230
0
        return;
19231
0
    draw_list->PushClipRect(board_min, board_max, true);
19232
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19233
0
    {
19234
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19235
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19236
0
        ImVec2 key_max = key_min + key_size;
19237
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19238
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19239
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19240
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19241
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19242
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19243
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19244
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19245
0
        if (IsKeyDown(key_data->Key))
19246
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19247
0
    }
19248
0
    draw_list->PopClipRect();
19249
0
}
19250
19251
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19252
void ImGui::DebugTextEncoding(const char* str)
19253
0
{
19254
0
    Text("Text: \"%s\"", str);
19255
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19256
0
        return;
19257
0
    TableSetupColumn("Offset");
19258
0
    TableSetupColumn("UTF-8");
19259
0
    TableSetupColumn("Glyph");
19260
0
    TableSetupColumn("Codepoint");
19261
0
    TableHeadersRow();
19262
0
    for (const char* p = str; *p != 0; )
19263
0
    {
19264
0
        unsigned int c;
19265
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19266
0
        TableNextColumn();
19267
0
        Text("%d", (int)(p - str));
19268
0
        TableNextColumn();
19269
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19270
0
        {
19271
0
            if (byte_index > 0)
19272
0
                SameLine();
19273
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19274
0
        }
19275
0
        TableNextColumn();
19276
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19277
0
            TextUnformatted(p, p + c_utf8_len);
19278
0
        else
19279
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19280
0
        TableNextColumn();
19281
0
        Text("U+%04X", (int)c);
19282
0
        p += c_utf8_len;
19283
0
    }
19284
0
    EndTable();
19285
0
}
19286
19287
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19288
static void MetricsHelpMarker(const char* desc)
19289
0
{
19290
0
    ImGui::TextDisabled("(?)");
19291
0
    if (ImGui::BeginItemTooltip())
19292
0
    {
19293
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19294
0
        ImGui::TextUnformatted(desc);
19295
0
        ImGui::PopTextWrapPos();
19296
0
        ImGui::EndTooltip();
19297
0
    }
19298
0
}
19299
19300
// [DEBUG] List fonts in a font atlas and display its texture
19301
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19302
0
{
19303
0
    for (ImFont* font : atlas->Fonts)
19304
0
    {
19305
0
        PushID(font);
19306
0
        DebugNodeFont(font);
19307
0
        PopID();
19308
0
    }
19309
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19310
0
    {
19311
0
        ImGuiContext& g = *GImGui;
19312
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19313
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19314
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19315
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19316
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19317
0
        TreePop();
19318
0
    }
19319
0
}
19320
19321
void ImGui::ShowMetricsWindow(bool* p_open)
19322
0
{
19323
0
    ImGuiContext& g = *GImGui;
19324
0
    ImGuiIO& io = g.IO;
19325
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19326
0
    if (cfg->ShowDebugLog)
19327
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19328
0
    if (cfg->ShowIDStackTool)
19329
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19330
19331
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19332
0
    {
19333
0
        End();
19334
0
        return;
19335
0
    }
19336
19337
    // Basic info
19338
0
    Text("Dear ImGui %s", GetVersion());
19339
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19340
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19341
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19342
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19343
19344
0
    Separator();
19345
19346
    // Debugging enums
19347
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19348
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19349
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19350
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19351
0
    if (cfg->ShowWindowsRectsType < 0)
19352
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19353
0
    if (cfg->ShowTablesRectsType < 0)
19354
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19355
19356
0
    struct Funcs
19357
0
    {
19358
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19359
0
        {
19360
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19361
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19362
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19363
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19364
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19365
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19366
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19367
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19368
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19369
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19370
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
19371
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
19372
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19373
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19374
0
            IM_ASSERT(0);
19375
0
            return ImRect();
19376
0
        }
19377
19378
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19379
0
        {
19380
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19381
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19382
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19383
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19384
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19385
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19386
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19387
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19388
0
            IM_ASSERT(0);
19389
0
            return ImRect();
19390
0
        }
19391
0
    };
19392
19393
    // Tools
19394
0
    if (TreeNode("Tools"))
19395
0
    {
19396
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19397
0
        SameLine();
19398
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19399
0
        if (show_encoding_viewer)
19400
0
        {
19401
0
            static char buf[100] = "";
19402
0
            SetNextItemWidth(-FLT_MIN);
19403
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19404
0
            if (buf[0] != 0)
19405
0
                DebugTextEncoding(buf);
19406
0
            TreePop();
19407
0
        }
19408
19409
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19410
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19411
0
            DebugStartItemPicker();
19412
0
        SameLine();
19413
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19414
19415
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19416
0
        SameLine();
19417
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19418
19419
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19420
0
        SameLine();
19421
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19422
19423
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19424
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19425
0
        SameLine();
19426
0
        SetNextItemWidth(GetFontSize() * 12);
19427
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19428
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19429
0
        {
19430
0
            BulletText("'%s':", g.NavWindow->Name);
19431
0
            Indent();
19432
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19433
0
            {
19434
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19435
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19436
0
            }
19437
0
            Unindent();
19438
0
        }
19439
19440
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19441
0
        SameLine();
19442
0
        SetNextItemWidth(GetFontSize() * 12);
19443
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19444
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19445
0
        {
19446
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19447
0
            {
19448
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19449
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19450
0
                    continue;
19451
19452
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19453
0
                if (IsItemHovered())
19454
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19455
0
                Indent();
19456
0
                char buf[128];
19457
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19458
0
                {
19459
0
                    if (rect_n >= TRT_ColumnsRect)
19460
0
                    {
19461
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19462
0
                            continue;
19463
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19464
0
                        {
19465
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19466
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19467
0
                            Selectable(buf);
19468
0
                            if (IsItemHovered())
19469
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19470
0
                        }
19471
0
                    }
19472
0
                    else
19473
0
                    {
19474
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19475
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19476
0
                        Selectable(buf);
19477
0
                        if (IsItemHovered())
19478
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19479
0
                    }
19480
0
                }
19481
0
                Unindent();
19482
0
            }
19483
0
        }
19484
19485
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19486
0
        SameLine();
19487
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19488
19489
0
        TreePop();
19490
0
    }
19491
19492
    // Windows
19493
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19494
0
    {
19495
        //SetNextItemOpen(true, ImGuiCond_Once);
19496
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19497
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19498
0
        if (TreeNode("By submission order (begin stack)"))
19499
0
        {
19500
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19501
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19502
0
            temp_buffer.resize(0);
19503
0
            for (ImGuiWindow* window : g.Windows)
19504
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
19505
0
                    temp_buffer.push_back(window);
19506
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19507
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19508
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19509
0
            TreePop();
19510
0
        }
19511
19512
0
        TreePop();
19513
0
    }
19514
19515
    // DrawLists
19516
0
    int drawlist_count = 0;
19517
0
    for (ImGuiViewportP* viewport : g.Viewports)
19518
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
19519
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19520
0
    {
19521
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19522
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19523
0
        for (ImGuiViewportP* viewport : g.Viewports)
19524
0
        {
19525
0
            bool viewport_has_drawlist = false;
19526
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
19527
0
            {
19528
0
                if (!viewport_has_drawlist)
19529
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19530
0
                viewport_has_drawlist = true;
19531
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
19532
0
            }
19533
0
        }
19534
0
        TreePop();
19535
0
    }
19536
19537
    // Viewports
19538
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19539
0
    {
19540
0
        Indent(GetTreeNodeToLabelSpacing());
19541
0
        RenderViewportsThumbnails();
19542
0
        Unindent(GetTreeNodeToLabelSpacing());
19543
19544
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19545
0
        SameLine();
19546
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19547
0
        if (open)
19548
0
        {
19549
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19550
0
            {
19551
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19552
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19553
0
                    i, mon.DpiScale * 100.0f,
19554
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19555
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19556
0
            }
19557
0
            TreePop();
19558
0
        }
19559
19560
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19561
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19562
0
        {
19563
0
            static ImVector<ImGuiViewportP*> viewports;
19564
0
            viewports.resize(g.Viewports.Size);
19565
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19566
0
            if (viewports.Size > 1)
19567
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19568
0
            for (ImGuiViewportP* viewport : viewports)
19569
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19570
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19571
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19572
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19573
0
            TreePop();
19574
0
        }
19575
0
        for (ImGuiViewportP* viewport : g.Viewports)
19576
0
            DebugNodeViewport(viewport);
19577
0
        TreePop();
19578
0
    }
19579
19580
    // Details for Popups
19581
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19582
0
    {
19583
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
19584
0
        {
19585
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19586
0
            ImGuiWindow* window = popup_data.Window;
19587
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19588
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19589
0
                popup_data.BackupNavWindow ? popup_data.BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19590
0
        }
19591
0
        TreePop();
19592
0
    }
19593
19594
    // Details for TabBars
19595
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19596
0
    {
19597
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19598
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19599
0
            {
19600
0
                PushID(tab_bar);
19601
0
                DebugNodeTabBar(tab_bar, "TabBar");
19602
0
                PopID();
19603
0
            }
19604
0
        TreePop();
19605
0
    }
19606
19607
    // Details for Tables
19608
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19609
0
    {
19610
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19611
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19612
0
                DebugNodeTable(table);
19613
0
        TreePop();
19614
0
    }
19615
19616
    // Details for Fonts
19617
0
    ImFontAtlas* atlas = g.IO.Fonts;
19618
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19619
0
    {
19620
0
        ShowFontAtlas(atlas);
19621
0
        TreePop();
19622
0
    }
19623
19624
    // Details for InputText
19625
0
    if (TreeNode("InputText"))
19626
0
    {
19627
0
        DebugNodeInputTextState(&g.InputTextState);
19628
0
        TreePop();
19629
0
    }
19630
19631
    // Details for TypingSelect
19632
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
19633
0
    {
19634
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
19635
0
        TreePop();
19636
0
    }
19637
19638
    // Details for Docking
19639
0
#ifdef IMGUI_HAS_DOCK
19640
0
    if (TreeNode("Docking"))
19641
0
    {
19642
0
        static bool root_nodes_only = true;
19643
0
        ImGuiDockContext* dc = &g.DockContext;
19644
0
        Checkbox("List root nodes", &root_nodes_only);
19645
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19646
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19647
0
        SameLine();
19648
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19649
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19650
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19651
0
                if (!root_nodes_only || node->IsRootNode())
19652
0
                    DebugNodeDockNode(node, "Node");
19653
0
        TreePop();
19654
0
    }
19655
0
#endif // #ifdef IMGUI_HAS_DOCK
19656
19657
    // Settings
19658
0
    if (TreeNode("Settings"))
19659
0
    {
19660
0
        if (SmallButton("Clear"))
19661
0
            ClearIniSettings();
19662
0
        SameLine();
19663
0
        if (SmallButton("Save to memory"))
19664
0
            SaveIniSettingsToMemory();
19665
0
        SameLine();
19666
0
        if (SmallButton("Save to disk"))
19667
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19668
0
        SameLine();
19669
0
        if (g.IO.IniFilename)
19670
0
            Text("\"%s\"", g.IO.IniFilename);
19671
0
        else
19672
0
            TextUnformatted("<NULL>");
19673
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19674
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19675
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19676
0
        {
19677
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
19678
0
                BulletText("\"%s\"", handler.TypeName);
19679
0
            TreePop();
19680
0
        }
19681
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19682
0
        {
19683
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19684
0
                DebugNodeWindowSettings(settings);
19685
0
            TreePop();
19686
0
        }
19687
19688
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19689
0
        {
19690
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19691
0
                DebugNodeTableSettings(settings);
19692
0
            TreePop();
19693
0
        }
19694
19695
0
#ifdef IMGUI_HAS_DOCK
19696
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19697
0
        {
19698
0
            ImGuiDockContext* dc = &g.DockContext;
19699
0
            Text("In SettingsWindows:");
19700
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19701
0
                if (settings->DockId != 0)
19702
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19703
0
            Text("In SettingsNodes:");
19704
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19705
0
            {
19706
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19707
0
                const char* selected_tab_name = NULL;
19708
0
                if (settings->SelectedTabId)
19709
0
                {
19710
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19711
0
                        selected_tab_name = window->Name;
19712
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19713
0
                        selected_tab_name = window_settings->GetName();
19714
0
                }
19715
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19716
0
            }
19717
0
            TreePop();
19718
0
        }
19719
0
#endif // #ifdef IMGUI_HAS_DOCK
19720
19721
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19722
0
        {
19723
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19724
0
            TreePop();
19725
0
        }
19726
0
        TreePop();
19727
0
    }
19728
19729
    // Settings
19730
0
    if (TreeNode("Memory allocations"))
19731
0
    {
19732
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
19733
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
19734
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
19735
0
        for (int n = buf_size - 1; n >= 0; n--)
19736
0
        {
19737
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
19738
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount);
19739
0
        }
19740
0
        TreePop();
19741
0
    }
19742
19743
0
    if (TreeNode("Inputs"))
19744
0
    {
19745
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19746
0
        {
19747
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19748
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19749
0
            Indent();
19750
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19751
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19752
#else
19753
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19754
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19755
#endif
19756
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19757
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19758
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19759
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19760
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19761
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19762
0
            Unindent();
19763
0
        }
19764
19765
0
        Text("MOUSE STATE");
19766
0
        {
19767
0
            Indent();
19768
0
            if (IsMousePosValid())
19769
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19770
0
            else
19771
0
                Text("Mouse pos: <INVALID>");
19772
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19773
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19774
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19775
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19776
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19777
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19778
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
19779
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19780
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19781
0
            Unindent();
19782
0
        }
19783
19784
0
        Text("MOUSE WHEELING");
19785
0
        {
19786
0
            Indent();
19787
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19788
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19789
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19790
0
            Unindent();
19791
0
        }
19792
19793
0
        Text("KEY OWNERS");
19794
0
        {
19795
0
            Indent();
19796
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19797
0
            {
19798
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19799
0
                {
19800
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19801
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19802
0
                        continue;
19803
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19804
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19805
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19806
0
                }
19807
0
                EndListBox();
19808
0
            }
19809
0
            Unindent();
19810
0
        }
19811
0
        Text("SHORTCUT ROUTING");
19812
0
        {
19813
0
            Indent();
19814
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19815
0
            {
19816
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19817
0
                {
19818
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19819
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19820
0
                    {
19821
0
                        char key_chord_name[64];
19822
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19823
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19824
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19825
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19826
0
                        idx = routing_data->NextEntryIndex;
19827
0
                    }
19828
0
                }
19829
0
                EndListBox();
19830
0
            }
19831
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19832
0
            Unindent();
19833
0
        }
19834
0
        TreePop();
19835
0
    }
19836
19837
0
    if (TreeNode("Internal state"))
19838
0
    {
19839
0
        Text("WINDOWING");
19840
0
        Indent();
19841
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19842
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19843
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19844
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19845
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19846
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19847
0
        Unindent();
19848
19849
0
        Text("ITEMS");
19850
0
        Indent();
19851
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19852
0
        DebugLocateItemOnHover(g.ActiveId);
19853
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19854
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19855
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19856
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
19857
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19858
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19859
0
        Unindent();
19860
19861
0
        Text("NAV,FOCUS");
19862
0
        Indent();
19863
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19864
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19865
0
        DebugLocateItemOnHover(g.NavId);
19866
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19867
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
19868
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19869
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
19870
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19871
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19872
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19873
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19874
0
        Unindent();
19875
19876
0
        TreePop();
19877
0
    }
19878
19879
    // Overlay: Display windows Rectangles and Begin Order
19880
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19881
0
    {
19882
0
        for (ImGuiWindow* window : g.Windows)
19883
0
        {
19884
0
            if (!window->WasActive)
19885
0
                continue;
19886
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19887
0
            if (cfg->ShowWindowsRects)
19888
0
            {
19889
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19890
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19891
0
            }
19892
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19893
0
            {
19894
0
                char buf[32];
19895
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19896
0
                float font_size = GetFontSize();
19897
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19898
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19899
0
            }
19900
0
        }
19901
0
    }
19902
19903
    // Overlay: Display Tables Rectangles
19904
0
    if (cfg->ShowTablesRects)
19905
0
    {
19906
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19907
0
        {
19908
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19909
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19910
0
                continue;
19911
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19912
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19913
0
            {
19914
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19915
0
                {
19916
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19917
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19918
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19919
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19920
0
                }
19921
0
            }
19922
0
            else
19923
0
            {
19924
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19925
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19926
0
            }
19927
0
        }
19928
0
    }
19929
19930
0
#ifdef IMGUI_HAS_DOCK
19931
    // Overlay: Display Docking info
19932
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19933
0
    {
19934
0
        char buf[64] = "";
19935
0
        char* p = buf;
19936
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19937
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19938
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19939
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19940
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19941
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19942
0
        int depth = DockNodeGetDepth(node);
19943
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19944
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19945
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19946
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19947
0
    }
19948
0
#endif // #ifdef IMGUI_HAS_DOCK
19949
19950
0
    End();
19951
0
}
19952
19953
// [DEBUG] Display contents of Columns
19954
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19955
0
{
19956
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19957
0
        return;
19958
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19959
0
    for (ImGuiOldColumnData& column : columns->Columns)
19960
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
19961
0
    TreePop();
19962
0
}
19963
19964
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19965
0
{
19966
0
    using namespace ImGui;
19967
0
    PushID(label);
19968
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19969
0
    Text("%s:", label);
19970
0
    if (!enabled)
19971
0
        BeginDisabled();
19972
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19973
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19974
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19975
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19976
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19977
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19978
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19979
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
19980
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
19981
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19982
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19983
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19984
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19985
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
19986
0
    if (!enabled)
19987
0
        EndDisabled();
19988
0
    PopStyleVar();
19989
0
    PopID();
19990
0
}
19991
19992
// [DEBUG] Display contents of ImDockNode
19993
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19994
0
{
19995
0
    ImGuiContext& g = *GImGui;
19996
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19997
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19998
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19999
0
    bool open;
20000
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20001
0
    if (node->Windows.Size > 0)
20002
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20003
0
    else
20004
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20005
0
    if (!is_alive) { PopStyleColor(); }
20006
0
    if (is_active && IsItemHovered())
20007
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20008
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20009
0
    if (open)
20010
0
    {
20011
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20012
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20013
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20014
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20015
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20016
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20017
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20018
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20019
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20020
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20021
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20022
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20023
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20024
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20025
0
        {
20026
0
            if (BeginTable("flags", 4))
20027
0
            {
20028
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20029
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20030
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20031
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20032
0
                EndTable();
20033
0
            }
20034
0
            TreePop();
20035
0
        }
20036
0
        if (node->ParentNode)
20037
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20038
0
        if (node->ChildNodes[0])
20039
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20040
0
        if (node->ChildNodes[1])
20041
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20042
0
        if (node->TabBar)
20043
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20044
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20045
20046
0
        TreePop();
20047
0
    }
20048
0
}
20049
20050
// [DEBUG] Display contents of ImDrawList
20051
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20052
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20053
0
{
20054
0
    ImGuiContext& g = *GImGui;
20055
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20056
0
    int cmd_count = draw_list->CmdBuffer.Size;
20057
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20058
0
        cmd_count--;
20059
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20060
0
    if (draw_list == GetWindowDrawList())
20061
0
    {
20062
0
        SameLine();
20063
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20064
0
        if (node_open)
20065
0
            TreePop();
20066
0
        return;
20067
0
    }
20068
20069
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20070
0
    if (window && IsItemHovered() && fg_draw_list)
20071
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20072
0
    if (!node_open)
20073
0
        return;
20074
20075
0
    if (window && !window->WasActive)
20076
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20077
20078
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20079
0
    {
20080
0
        if (pcmd->UserCallback)
20081
0
        {
20082
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20083
0
            continue;
20084
0
        }
20085
20086
0
        char buf[300];
20087
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20088
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
20089
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20090
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20091
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20092
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20093
0
        if (!pcmd_node_open)
20094
0
            continue;
20095
20096
        // Calculate approximate coverage area (touched pixel count)
20097
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20098
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20099
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20100
0
        float total_area = 0.0f;
20101
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20102
0
        {
20103
0
            ImVec2 triangle[3];
20104
0
            for (int n = 0; n < 3; n++, idx_n++)
20105
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20106
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20107
0
        }
20108
20109
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20110
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20111
0
        Selectable(buf);
20112
0
        if (IsItemHovered() && fg_draw_list)
20113
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20114
20115
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20116
0
        ImGuiListClipper clipper;
20117
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20118
0
        while (clipper.Step())
20119
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20120
0
            {
20121
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20122
0
                ImVec2 triangle[3];
20123
0
                for (int n = 0; n < 3; n++, idx_i++)
20124
0
                {
20125
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20126
0
                    triangle[n] = v.pos;
20127
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20128
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20129
0
                }
20130
20131
0
                Selectable(buf, false);
20132
0
                if (fg_draw_list && IsItemHovered())
20133
0
                {
20134
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20135
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20136
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20137
0
                    fg_draw_list->Flags = backup_flags;
20138
0
                }
20139
0
            }
20140
0
        TreePop();
20141
0
    }
20142
0
    TreePop();
20143
0
}
20144
20145
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20146
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20147
0
{
20148
0
    IM_ASSERT(show_mesh || show_aabb);
20149
20150
    // Draw wire-frame version of all triangles
20151
0
    ImRect clip_rect = draw_cmd->ClipRect;
20152
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20153
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20154
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20155
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20156
0
    {
20157
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20158
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20159
20160
0
        ImVec2 triangle[3];
20161
0
        for (int n = 0; n < 3; n++, idx_n++)
20162
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20163
0
        if (show_mesh)
20164
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20165
0
    }
20166
    // Draw bounding boxes
20167
0
    if (show_aabb)
20168
0
    {
20169
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20170
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20171
0
    }
20172
0
    out_draw_list->Flags = backup_flags;
20173
0
}
20174
20175
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20176
void ImGui::DebugNodeFont(ImFont* font)
20177
0
{
20178
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20179
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20180
0
    SameLine();
20181
0
    if (SmallButton("Set as default"))
20182
0
        GetIO().FontDefault = font;
20183
0
    if (!opened)
20184
0
        return;
20185
20186
    // Display preview text
20187
0
    PushFont(font);
20188
0
    Text("The quick brown fox jumps over the lazy dog");
20189
0
    PopFont();
20190
20191
    // Display details
20192
0
    SetNextItemWidth(GetFontSize() * 8);
20193
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20194
0
    SameLine(); MetricsHelpMarker(
20195
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
20196
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20197
0
        "You may oversample them to get some flexibility with scaling. "
20198
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20199
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20200
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20201
0
    char c_str[5];
20202
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20203
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20204
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20205
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20206
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20207
0
        if (font->ConfigData)
20208
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20209
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20210
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20211
20212
    // Display all glyphs of the fonts in separate pages of 256 characters
20213
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20214
0
    {
20215
0
        ImDrawList* draw_list = GetWindowDrawList();
20216
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20217
0
        const float cell_size = font->FontSize * 1;
20218
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20219
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20220
0
        {
20221
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20222
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20223
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20224
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20225
0
            {
20226
0
                base += 4096 - 256;
20227
0
                continue;
20228
0
            }
20229
20230
0
            int count = 0;
20231
0
            for (unsigned int n = 0; n < 256; n++)
20232
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20233
0
                    count++;
20234
0
            if (count <= 0)
20235
0
                continue;
20236
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20237
0
                continue;
20238
20239
            // Draw a 16x16 grid of glyphs
20240
0
            ImVec2 base_pos = GetCursorScreenPos();
20241
0
            for (unsigned int n = 0; n < 256; n++)
20242
0
            {
20243
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20244
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20245
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20246
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20247
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20248
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20249
0
                if (!glyph)
20250
0
                    continue;
20251
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20252
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20253
0
                {
20254
0
                    DebugNodeFontGlyph(font, glyph);
20255
0
                    EndTooltip();
20256
0
                }
20257
0
            }
20258
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20259
0
            TreePop();
20260
0
        }
20261
0
        TreePop();
20262
0
    }
20263
0
    TreePop();
20264
0
}
20265
20266
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20267
0
{
20268
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20269
0
    Separator();
20270
0
    Text("Visible: %d", glyph->Visible);
20271
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20272
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20273
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20274
0
}
20275
20276
// [DEBUG] Display contents of ImGuiStorage
20277
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20278
0
{
20279
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20280
0
        return;
20281
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20282
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20283
0
    TreePop();
20284
0
}
20285
20286
// [DEBUG] Display contents of ImGuiTabBar
20287
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20288
0
{
20289
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20290
0
    char buf[256];
20291
0
    char* p = buf;
20292
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20293
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20294
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20295
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20296
0
    {
20297
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20298
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20299
0
    }
20300
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20301
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20302
0
    bool open = TreeNode(label, "%s", buf);
20303
0
    if (!is_active) { PopStyleColor(); }
20304
0
    if (is_active && IsItemHovered())
20305
0
    {
20306
0
        ImDrawList* draw_list = GetForegroundDrawList();
20307
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20308
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20309
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20310
0
    }
20311
0
    if (open)
20312
0
    {
20313
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20314
0
        {
20315
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20316
0
            PushID(tab);
20317
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20318
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20319
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20320
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20321
0
            PopID();
20322
0
        }
20323
0
        TreePop();
20324
0
    }
20325
0
}
20326
20327
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20328
0
{
20329
0
    SetNextItemOpen(true, ImGuiCond_Once);
20330
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20331
0
    {
20332
0
        ImGuiWindowFlags flags = viewport->Flags;
20333
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20334
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20335
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20336
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20337
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20338
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20339
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20340
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20341
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20342
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20343
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20344
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20345
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20346
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20347
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20348
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20349
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20350
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20351
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20352
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20353
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20354
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20355
0
        TreePop();
20356
0
    }
20357
0
}
20358
20359
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20360
0
{
20361
0
    if (window == NULL)
20362
0
    {
20363
0
        BulletText("%s: NULL", label);
20364
0
        return;
20365
0
    }
20366
20367
0
    ImGuiContext& g = *GImGui;
20368
0
    const bool is_active = window->WasActive;
20369
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20370
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20371
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20372
0
    if (!is_active) { PopStyleColor(); }
20373
0
    if (IsItemHovered() && is_active)
20374
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20375
0
    if (!open)
20376
0
        return;
20377
20378
0
    if (window->MemoryCompacted)
20379
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20380
20381
0
    ImGuiWindowFlags flags = window->Flags;
20382
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20383
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20384
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20385
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20386
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20387
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20388
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20389
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20390
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20391
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20392
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20393
0
    {
20394
0
        ImRect r = window->NavRectRel[layer];
20395
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20396
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20397
0
        else
20398
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20399
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20400
0
    }
20401
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20402
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20403
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20404
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20405
20406
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20407
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20408
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20409
0
    if (window->DockNode || window->DockNodeAsHost)
20410
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20411
20412
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20413
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20414
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20415
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20416
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20417
0
    {
20418
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
20419
0
            DebugNodeColumns(&columns);
20420
0
        TreePop();
20421
0
    }
20422
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20423
0
    TreePop();
20424
0
}
20425
20426
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20427
0
{
20428
0
    if (settings->WantDelete)
20429
0
        BeginDisabled();
20430
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20431
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20432
0
    if (settings->WantDelete)
20433
0
        EndDisabled();
20434
0
}
20435
20436
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20437
0
{
20438
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20439
0
        return;
20440
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20441
0
    {
20442
0
        PushID((*windows)[i]);
20443
0
        DebugNodeWindow((*windows)[i], "Window");
20444
0
        PopID();
20445
0
    }
20446
0
    TreePop();
20447
0
}
20448
20449
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20450
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20451
0
{
20452
0
    for (int i = 0; i < windows_size; i++)
20453
0
    {
20454
0
        ImGuiWindow* window = windows[i];
20455
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20456
0
            continue;
20457
0
        char buf[20];
20458
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20459
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20460
0
        DebugNodeWindow(window, buf);
20461
0
        Indent();
20462
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20463
0
        Unindent();
20464
0
    }
20465
0
}
20466
20467
//-----------------------------------------------------------------------------
20468
// [SECTION] DEBUG LOG WINDOW
20469
//-----------------------------------------------------------------------------
20470
20471
void ImGui::DebugLog(const char* fmt, ...)
20472
0
{
20473
0
    va_list args;
20474
0
    va_start(args, fmt);
20475
0
    DebugLogV(fmt, args);
20476
0
    va_end(args);
20477
0
}
20478
20479
void ImGui::DebugLogV(const char* fmt, va_list args)
20480
0
{
20481
0
    ImGuiContext& g = *GImGui;
20482
0
    const int old_size = g.DebugLogBuf.size();
20483
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20484
0
    g.DebugLogBuf.appendfv(fmt, args);
20485
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20486
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20487
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20488
#ifdef IMGUI_ENABLE_TEST_ENGINE
20489
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
20490
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
20491
#endif
20492
0
}
20493
20494
void ImGui::ShowDebugLogWindow(bool* p_open)
20495
0
{
20496
0
    ImGuiContext& g = *GImGui;
20497
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20498
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20499
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20500
0
    {
20501
0
        End();
20502
0
        return;
20503
0
    }
20504
20505
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20506
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20507
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20508
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20509
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20510
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20511
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20512
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20513
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20514
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20515
20516
0
    if (SmallButton("Clear"))
20517
0
    {
20518
0
        g.DebugLogBuf.clear();
20519
0
        g.DebugLogIndex.clear();
20520
0
    }
20521
0
    SameLine();
20522
0
    if (SmallButton("Copy"))
20523
0
        SetClipboardText(g.DebugLogBuf.c_str());
20524
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20525
20526
0
    ImGuiListClipper clipper;
20527
0
    clipper.Begin(g.DebugLogIndex.size());
20528
0
    while (clipper.Step())
20529
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20530
0
        {
20531
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20532
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20533
0
            TextUnformatted(line_begin, line_end);
20534
0
            ImRect text_rect = g.LastItemData.Rect;
20535
0
            if (IsItemHovered())
20536
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20537
0
                {
20538
0
                    ImGuiID id = 0;
20539
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20540
0
                        continue;
20541
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20542
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20543
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20544
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20545
0
                        DebugLocateItemOnHover(id);
20546
0
                    p += 10;
20547
0
                }
20548
0
        }
20549
0
    if (GetScrollY() >= GetScrollMaxY())
20550
0
        SetScrollHereY(1.0f);
20551
0
    EndChild();
20552
20553
0
    End();
20554
0
}
20555
20556
//-----------------------------------------------------------------------------
20557
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
20558
//-----------------------------------------------------------------------------
20559
20560
// Draw a small cross at current CursorPos in current window's DrawList
20561
void ImGui::DebugDrawCursorPos(ImU32 col)
20562
0
{
20563
0
    ImGuiContext& g = *GImGui;
20564
0
    ImGuiWindow* window = g.CurrentWindow;
20565
0
    ImVec2 pos = window->DC.CursorPos;
20566
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
20567
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
20568
0
}
20569
20570
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
20571
void ImGui::DebugDrawLineExtents(ImU32 col)
20572
0
{
20573
0
    ImGuiContext& g = *GImGui;
20574
0
    ImGuiWindow* window = g.CurrentWindow;
20575
0
    float curr_x = window->DC.CursorPos.x;
20576
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
20577
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
20578
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
20579
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
20580
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
20581
0
}
20582
20583
// Draw last item rect in ForegroundDrawList (so it is always visible)
20584
void ImGui::DebugDrawItemRect(ImU32 col)
20585
0
{
20586
0
    ImGuiContext& g = *GImGui;
20587
0
    ImGuiWindow* window = g.CurrentWindow;
20588
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
20589
0
}
20590
20591
// [DEBUG] Locate item position/rectangle given an ID.
20592
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20593
20594
void ImGui::DebugLocateItem(ImGuiID target_id)
20595
0
{
20596
0
    ImGuiContext& g = *GImGui;
20597
0
    g.DebugLocateId = target_id;
20598
0
    g.DebugLocateFrames = 2;
20599
0
}
20600
20601
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20602
0
{
20603
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20604
0
        return;
20605
0
    ImGuiContext& g = *GImGui;
20606
0
    DebugLocateItem(target_id);
20607
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20608
0
}
20609
20610
void ImGui::DebugLocateItemResolveWithLastItem()
20611
0
{
20612
0
    ImGuiContext& g = *GImGui;
20613
0
    ImGuiLastItemData item_data = g.LastItemData;
20614
0
    g.DebugLocateId = 0;
20615
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20616
0
    ImRect r = item_data.Rect;
20617
0
    r.Expand(3.0f);
20618
0
    ImVec2 p1 = g.IO.MousePos;
20619
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20620
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20621
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20622
0
}
20623
20624
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20625
void ImGui::UpdateDebugToolItemPicker()
20626
54.1k
{
20627
54.1k
    ImGuiContext& g = *GImGui;
20628
54.1k
    g.DebugItemPickerBreakId = 0;
20629
54.1k
    if (!g.DebugItemPickerActive)
20630
54.1k
        return;
20631
20632
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20633
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20634
0
    if (IsKeyPressed(ImGuiKey_Escape))
20635
0
        g.DebugItemPickerActive = false;
20636
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20637
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20638
0
    {
20639
0
        g.DebugItemPickerBreakId = hovered_id;
20640
0
        g.DebugItemPickerActive = false;
20641
0
    }
20642
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20643
0
        if (change_mapping && IsMouseClicked(mouse_button))
20644
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20645
0
    SetNextWindowBgAlpha(0.70f);
20646
0
    if (!BeginTooltip())
20647
0
        return;
20648
0
    Text("HoveredId: 0x%08X", hovered_id);
20649
0
    Text("Press ESC to abort picking.");
20650
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20651
0
    if (change_mapping)
20652
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20653
0
    else
20654
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20655
0
    EndTooltip();
20656
0
}
20657
20658
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
20659
void ImGui::UpdateDebugToolStackQueries()
20660
54.1k
{
20661
54.1k
    ImGuiContext& g = *GImGui;
20662
54.1k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20663
20664
    // Clear hook when id stack tool is not visible
20665
54.1k
    g.DebugHookIdInfo = 0;
20666
54.1k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20667
54.1k
        return;
20668
20669
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20670
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20671
4
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20672
4
    if (tool->QueryId != query_id)
20673
0
    {
20674
0
        tool->QueryId = query_id;
20675
0
        tool->StackLevel = -1;
20676
0
        tool->Results.resize(0);
20677
0
    }
20678
4
    if (query_id == 0)
20679
4
        return;
20680
20681
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20682
0
    int stack_level = tool->StackLevel;
20683
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20684
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20685
0
            tool->StackLevel++;
20686
20687
    // Update hook
20688
0
    stack_level = tool->StackLevel;
20689
0
    if (stack_level == -1)
20690
0
        g.DebugHookIdInfo = query_id;
20691
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20692
0
    {
20693
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20694
0
        tool->Results[stack_level].QueryFrameCount++;
20695
0
    }
20696
0
}
20697
20698
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
20699
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20700
0
{
20701
0
    ImGuiContext& g = *GImGui;
20702
0
    ImGuiWindow* window = g.CurrentWindow;
20703
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20704
20705
    // Step 0: stack query
20706
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20707
0
    if (tool->StackLevel == -1)
20708
0
    {
20709
0
        tool->StackLevel++;
20710
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20711
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20712
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20713
0
        return;
20714
0
    }
20715
20716
    // Step 1+: query for individual level
20717
0
    IM_ASSERT(tool->StackLevel >= 0);
20718
0
    if (tool->StackLevel != window->IDStack.Size)
20719
0
        return;
20720
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20721
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20722
20723
0
    switch (data_type)
20724
0
    {
20725
0
    case ImGuiDataType_S32:
20726
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20727
0
        break;
20728
0
    case ImGuiDataType_String:
20729
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20730
0
        break;
20731
0
    case ImGuiDataType_Pointer:
20732
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20733
0
        break;
20734
0
    case ImGuiDataType_ID:
20735
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20736
0
            return;
20737
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20738
0
        break;
20739
0
    default:
20740
0
        IM_ASSERT(0);
20741
0
    }
20742
0
    info->QuerySuccess = true;
20743
0
    info->DataType = data_type;
20744
0
}
20745
20746
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20747
0
{
20748
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20749
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20750
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20751
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20752
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20753
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20754
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20755
0
        return (*buf = 0);
20756
#ifdef IMGUI_ENABLE_TEST_ENGINE
20757
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20758
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20759
#endif
20760
0
    return ImFormatString(buf, buf_size, "???");
20761
0
}
20762
20763
// ID Stack Tool: Display UI
20764
void ImGui::ShowIDStackToolWindow(bool* p_open)
20765
0
{
20766
0
    ImGuiContext& g = *GImGui;
20767
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20768
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20769
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20770
0
    {
20771
0
        End();
20772
0
        return;
20773
0
    }
20774
20775
    // Display hovered/active status
20776
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20777
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20778
0
    const ImGuiID active_id = g.ActiveId;
20779
#ifdef IMGUI_ENABLE_TEST_ENGINE
20780
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20781
#else
20782
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20783
0
#endif
20784
0
    SameLine();
20785
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20786
20787
    // CTRL+C to copy path
20788
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20789
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20790
0
    SameLine();
20791
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20792
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20793
0
    {
20794
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20795
0
        char* p = g.TempBuffer.Data;
20796
0
        char* p_end = p + g.TempBuffer.Size;
20797
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20798
0
        {
20799
0
            *p++ = '/';
20800
0
            char level_desc[256];
20801
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20802
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20803
0
            {
20804
0
                if (level_desc[n] == '/')
20805
0
                    *p++ = '\\';
20806
0
                *p++ = level_desc[n];
20807
0
            }
20808
0
        }
20809
0
        *p = '\0';
20810
0
        SetClipboardText(g.TempBuffer.Data);
20811
0
    }
20812
20813
    // Display decorated stack
20814
0
    tool->LastActiveFrame = g.FrameCount;
20815
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20816
0
    {
20817
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20818
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20819
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20820
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20821
0
        TableHeadersRow();
20822
0
        for (int n = 0; n < tool->Results.Size; n++)
20823
0
        {
20824
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20825
0
            TableNextColumn();
20826
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20827
0
            TableNextColumn();
20828
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20829
0
            TextUnformatted(g.TempBuffer.Data);
20830
0
            TableNextColumn();
20831
0
            Text("0x%08X", info->ID);
20832
0
            if (n == tool->Results.Size - 1)
20833
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20834
0
        }
20835
0
        EndTable();
20836
0
    }
20837
0
    End();
20838
0
}
20839
20840
#else
20841
20842
void ImGui::ShowMetricsWindow(bool*) {}
20843
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20844
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20845
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20846
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20847
void ImGui::DebugNodeFont(ImFont*) {}
20848
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20849
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20850
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20851
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20852
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20853
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20854
20855
void ImGui::DebugLog(const char*, ...) {}
20856
void ImGui::DebugLogV(const char*, va_list) {}
20857
void ImGui::ShowDebugLogWindow(bool*) {}
20858
void ImGui::ShowIDStackToolWindow(bool*) {}
20859
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20860
void ImGui::UpdateDebugToolItemPicker() {}
20861
void ImGui::UpdateDebugToolStackQueries() {}
20862
20863
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20864
20865
//-----------------------------------------------------------------------------
20866
20867
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20868
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20869
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20870
#include "imgui_user.inl"
20871
#endif
20872
20873
//-----------------------------------------------------------------------------
20874
20875
#endif // #ifndef IMGUI_DISABLE